possible combination in binary counting

You can choose between two operations. For N-1 times. That gives you 2^(N-1) possible combinations. Just loop over all those combinations with a simple integer. Then decide wether you choose plus or minus by looking at the nth bit of the iterating number.

int N = ...; 
int max = 1 << (N-1); // 2^(N-1)
for (int i = 0; i < max; ++i) // loop over all + and - combinations
{
   // start at 1, since you can't put a - in front of the first digit
   int sum = 1;
   for (int k = 2; k <= N; ++k)
   {
       if (((i >> (k - 2)) & 1) == 1) // look at bit (k-2)
       {
           sum += k;
       } else
       {
           sum -= k;
       }
   }

   if (sum == 0)
   {
       // we found a solution, print binary output:
       // 1 means +, 0 means -
       // read from right to left!
       System.out.println(Integer.toString(i, 2));
   }
}

If this outputs for example:

100101

Then you have:

+--+-+

Insert the numbers here from right to left:

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

Leave a Comment