下面贴出源码:
package cn.zimo.algorithm;
import java.util.Arrays;
import java.util.Scanner;
/**
* 6174问题
* @author 子墨
* @date 2018年5月6日 上午10:04:34
*/
public class Demo27 {
public static void main(String[] args) {
int[] num=new int[2000];
int count=1;
String str=new Scanner(System.in).nextLine();
num[0]=Integer.parseInt(str);
while(true) {
boolean found=false;
num[count]=getNext(num[count-1]+"");
if(count==1) {
System.out.print(num[0]);
}
System.out.print("->"+num[count]);
for(int i=0;i<count;i++) {
if(num[count]==num[i]) {
found=true;
break;
}
}
if(found) {
break;
}
count++;
}
System.out.println();
}
public static int reverse(int[] arr) {
String temp="";
for(int i=arr.length-1;i>=0;i--) {
temp+=arr[i];
}
return Integer.parseInt(temp);
}
public static int order(int[] arr) {
String temp="";
for(int i=0;i<arr.length;i++) {
temp+=arr[i];
}
return Integer.parseInt(temp);
}
public static int getNext(String str) {
int[] arr=new int[str.length()];
for(int i=0;i<str.length();i++) {
arr[i]=Integer.parseInt(str.charAt(i)+"");
}
Arrays.sort(arr);
return reverse(arr)-order(arr);
}
}