找到给定条件的最小可能数组

时间:2017-05-29 00:53:49

标签: java

我有一个数组说int[] x = {1,0,0,2,0,2}。每个元素的pow(2,x [i])之和为13。 我想找到满足相同条件的最小可能数组(每个元素的平方和应为13)。 请帮帮我。

1 个答案:

答案 0 :(得分:0)

public void solution(){

    double equation = 0;
    int[] a = new int[] { 2, 1, 0, 5, 2, 3 };
    try {

        for (int i = 0; i < a.length; i++) {
            equation = equation + Math.pow(2, a[i]);
        }
        System.out.println(equation);

        int equation1 = (int) equation;
        int binaryArray[] = new int[30];
        int i = 0;
        while (equation1 > 0) {

            binaryArray[i++] = equation1 % 2;
            equation1 = equation1 / 2;

        }
        int sum = 0;
        List<Integer> list = new ArrayList<Integer>();
        do {
            for (int j = i - 1; j >= 0; j--) {
                if (binaryArray[j] == 0) {
                    i--;
                    continue;
                }
                sum = sum + (binaryArray[j] * (int) Math.pow(2, i));
                i--;
                list.add(i);
            }
        } while (i > 0);
        // shortest list
        System.out.println(list);
        // length of shortest list
        System.out.println(list.size());

    } finally {

    }

}