java 任意花朵数算法

/**
 * 花朵数,网友算法下载学习
 * @author cxcx
 *
 */
public class Arithmetic11 {
    private static BigInteger[] table = new BigInteger[10];
 
    public static void main(String[] args) {
        long time = System.nanoTime();
        find(21);
        time = System.nanoTime() - time;
        System.out.println(time / 1000000000.0 + "s");
    }
 
    public static void find(int n) {
        for (int i = 0; i < 10; i++)
            table[i] = BigInteger.valueOf(i).pow(n);
        int[] nums = new int[n];
        int index = 0;
        int num = 0;
        BigInteger sum = BigInteger.ZERO;
        BigInteger MIN = BigInteger.TEN.pow(n - 1);
        BigInteger MAX = BigInteger.TEN.pow(n).subtract(BigInteger.ONE);
        while (true) {
            if (index < nums.length && num < 10) {
                BigInteger temp = sum.add(table[num]);
                if (temp.compareTo(MAX) < 0) {
                    nums[index] = num;
                    index++;
                    sum = temp;
                    continue;
                }
            } else if (index >= nums.length && sum.compareTo(MIN) > 0) {
                int[] temp = getArray(sum);
                if (check(nums, true, temp, false))
                    System.out.println(sum);
            } else if (index <= 0) {
                break;
            }
            index--;
            num = nums[index];
            sum = sum.subtract(table[num]);
            num++;
        }
    }
 
    public static boolean check(int[] a1, boolean copy1, int[] a2, boolean copy2) {
        if (a1.length != a2.length)
            return false;
        if (copy1)
            a1 = a1.clone();
        if (copy2)
            a2 = a2.clone();
        Arrays.sort(a1);
        Arrays.sort(a2);
        return Arrays.equals(a1, a2);
    }
 
    public static int[] getArray(BigInteger big) {
        String s = String.valueOf(big);
        int length = s.length();
        int[] res = new int[length];
        for (int i = 0; i < length; i++)
            res[i] = s.charAt(i) - '0';
        return res;
    }
}

算法参考:http://bbs.csdn.net/topics/360185693


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值