数字黑洞

来源:互联网 发布:php ftp服务器 编辑:程序博客网 时间:2024/04/27 22:00

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

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

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

[82962, 75933, 63954,61974]

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

public class 数字黑洞 {public static final int ASC = 0;public static final int DESC = 1;public static ArrayList<Integer> findOut(int num){LinkedHashMap<Integer,Integer> numInfo = new LinkedHashMap<Integer,Integer>();//key为结果数字, value为此结果出现的次数find(num,numInfo);ArrayList<Integer> heiDong = new ArrayList<Integer>();for(Map.Entry<Integer,Integer> e : numInfo.entrySet()){//如果一个数重复出现, 则说明此数是数字黑洞的一部分if(e.getValue() > 1)heiDong.add(e.getKey());}return heiDong;}private static void find(int num,Map<Integer,Integer> numInfo){int[] nums = fj(num ,5);order(nums, 数字黑洞.ASC);int min = hb(nums );order(nums, 数字黑洞.DESC);int max = hb(nums );int n = max - min;int ciShu = null == numInfo.get(n)? 0 : numInfo.get(n);//如果得到的数出现的次数小于2一则记录下此数if(ciShu < 2){numInfo.put(n,ciShu + 1);find(n, numInfo);}}//整数合并private static int hb(int[] nums){int num = 0;for(int i = nums.length - 1,j = 1; i > -1; i--,j*=10 )num += nums[i] * j;return num;}//整数分解private static int[] fj(int num , int len){String numStr = num + "";int[] nums = new int[len];int n = len - numStr.length();for(int i = n ; i < len; i++)nums[i] = numStr.charAt(i - n) - '0'; return nums;}private static void order(int[] nums,int type){int j,x;boolean isDESC = false;if(type == DESC)isDESC = true;for(int i = 0; i < nums.length - 1; i++){if((nums[i] < nums[i + 1] && isDESC) || (nums[i] > nums[i + 1] && !isDESC)){j = i + 1;x = nums[j];do{nums[j] = nums[j - 1];}while(--j > 0 && ((x > nums[j - 1] && isDESC) || (x < nums[j - 1] && !isDESC)));nums[j] = x;}}}public static void main(String[] args) {System.out.println(数字黑洞.findOut(34256));}}