How to get a number from a list of numbers by using + or - operations

▼魔方 西西 提交于 2019-12-08 01:18:41

问题


In my question, we are given a number and list of numbers and we are supposed to get the first number from the given list of numbers by using the operations + or -

For Example: -1 is the target number 1 2 3 5 are numbers given to get -1 solution should be -1+2+3-5 = -1 or -1-2-3+5 = -1

Limits for target number is from -180 to +180 and the limit for list of numbers is from 2 to 20

To find the solution what kind of algorithm should be used? If I want to use generate all the possibilities will it be efficient? And is the any binary solution of this problem?

Thanks for your help


回答1:


Number of possibpe variants is 2^20; Let's generate all numbers from 0 to 2^N. Binary representation of these numbers will be 00000(20 zeroes), 000...01,0000.10,...,1111(20 ones). Imagine, that each zero is minus and one is a plus.

    int target = -1;
    int[] numbers = new int[20];
    Arrays.fill(numbers, 0);

    numbers[0] = 1;
    numbers[1] = 2;
    numbers[2] = 3;
    numbers[3] = 5;
    for(int i=0;i<(1<<20);i++) //masks from 00...00 to 11...11 (from --...--- to ++...+++)
    {
        int sum=0;
        for(int bit=0;bit<20;bit++)
        {
            if(((1<<bit)&i)>0)
            {
                sum+=numbers[bit];
            }
            else
            {
                sum-=numbers[bit];
            }
        }
        if(sum==target)
        {
            System.out.print(target+" = ");
            for(int bit=0;bit<20;bit++)
            {
            if(((1<<bit)&i)>0)
            {
                System.out.print("+"+numbers[bit]);
            }
            else
            {
                System.out.print("-"+numbers[bit]);
            }
            }
            break;
        }
    }

Output: -1 = -1+2+3-5-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0



来源:https://stackoverflow.com/questions/18586154/how-to-get-a-number-from-a-list-of-numbers-by-using-or-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!