java - possible combination in binary counting -


consider sequence of digits 1 through n (n<=9) in increasing order:   1 2 3 4  … n insert either ‘+’ (for addition) or ‘-‘ (for subtraction) between each of digits resultant sum zero. print possible combinations sum zero.

you can choose between 2 operations. n-1 times. gives 2^(n-1) possible combinations. loop on combinations simple integer. decide wether choose plus or minus looking @ nth bit of iterating number.

int n = ...;  int max = 1 << (n-1); // 2^(n-1) (int = 0; < max; ++i) // loop on + , - combinations {    // start @ 1, since can't put - in front of first digit    int sum = 1;    (int k = 2; k <= n; ++k)    {        if (((i >> (k - 2)) & 1) == 1) // @ bit (k-2)        {            sum += k;        } else        {            sum -= k;        }    }     if (sum == 0)    {        // found solution, print binary output:        // 1 means +, 0 means -        // read right left!        system.out.println(integer.tostring(i, 2));    } } 

if outputs example:

100101 

then have:

+--+-+ 

insert numbers here right left:

7+6-5-4+3-2+1 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -