任意一个5位数,比如:34256,把它的各位数字打乱,重新排列,可以得到一个最大的数:65432,一个最小的数23456。求这两个数字的差,得:41976,把这个数字再次重复上述过程(如果不足5位,则前边补0)。如此往复,数字会落入某个循环圈(称为数字黑洞)。

比如,刚才的数字会落入:[82962, 75933, 63954, 61974] 这个循环圈。

请编写程序,找到5位数所有可能的循环圈,并输出,每个循环圈占1行。其中5位数全都相同则循环圈为 [0],这个可以不考虑。

循环圈的输出格式仿照:

[82962, 75933, 63954, 61974]

其中数字的先后顺序可以不考虑。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet; public class Main {
public static HashSet<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();
public static int start; public String getMax(int n) {
StringBuffer s = new StringBuffer("");
String temp = "" + n;
if(temp.length() < 5) {
while(temp.length() < 5) {
temp = "0" + temp;
}
}
char[] arrayN = temp.toCharArray();
Arrays.sort(arrayN);
for(int i = arrayN.length - 1;i >= 0;i--)
s.append(arrayN[i]);
return s.toString();
} public String getMin(int n) {
String temp = getMax(n);
StringBuffer s = new StringBuffer(temp);
return s.reverse().toString();
} public int getResult(int n) {
int max = Integer.valueOf(getMax(n));
int min = Integer.valueOf(getMin(n));
return max - min;
} public static void main(String[] args) {
Main test = new Main();
for(int i = 10000;i < 100000;i++) {
if(i % 11111 == 0)
continue;
ArrayList<Integer> list = new ArrayList<Integer>();
int a = i;
while(true) {
a = test.getResult(a);
if(!list.contains(a))
list.add(a);
else
break;
}
start = list.indexOf(a);
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int j = start;j < list.size();j++)
temp.add(list.get(j));
Collections.sort(temp);
set.add(temp);
}
for(ArrayList<Integer> list : set)
System.out.println(list);
}
}
05-12 17:06