日期:2014-05-20  浏览次数:20778 次

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

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


------解决方案--------------------
手边开着VS就直接用C#写了,再补个Java版的吧:
Java code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class NumberTest {
    public static void main(String[] args) throws Exception {
        StringBuilder temp = new StringBuilder();
        Set<String> set = new HashSet<String>();
        int[] a = { 11111, 34256 };

        for (int i : a) {
            List<Integer> list = getCircle(i);

            if (list.size() > 0) {
                temp.delete(0, temp.length());

                temp.append('[');
                for (Integer num : list)
                    temp.append(num + ",");
                temp.append(8 + "]");

                set.add(temp.toString());
            }
        }

        for (String str : set)
            System.out.println(str);
    }

    static List<Integer> getCircle(int num) throws Exception {
        List<Integer> circle = new ArrayList<Integer>();

        while (true) {
            num = getNextNumber(num);

            if (circle.contains(num)) {
                while (circle.indexOf(num) > 0)
                    circle.remove(0);

                return (circle);
            }

            circle.add(num);
        }
    }

    static int getNextNumber(int num) throws Exception {
        List<Integer> temp = new ArrayList<Integer>();
        Object[] nums;
        int big = 0, small = 0;

        if (num < 0)
            throw new Exception("参数错误");

        while (num > 0) {
            temp.add(num % 10);
            num /= 10;
        }

        nums = temp.toArray();
        Arrays.sort(nums);

        for (Object n : nums)
            small = small * 10 + (Integer) n;

        for (int i = nums.length - 1; i >= 0; i--)
            big = big * 10 + (Integer) nums[i];

        return (big - small);
    }
}