-1

These days,in the solution section of many algorithmic challenges,I see this particular phrase 1<<j,which is sometimes given as an exit condition for a for-loop, what is the significance of these i<(1<<n) and 1<<j?

For example :

for(i=0;i<**(1<<n)**;i++)
       {
        sum=0;
          for(j=0;j<n;j++)
          {
            if(i&**(1<<j)**)
            {
             sum+=a[j];
            }
          }
          if(sum==m)
          {
             flag=1;
             break;
          }
       }

edit:by "what is 1<<j ",I meant to what extent does the loop go?

  • 2
    Possible duplicate of [What are bitwise shift (bit-shift) operators and how do they work?](http://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work) – tkausl Nov 22 '16 at 08:24
  • This answers what a shift is and thats what you are asking essentially. – tkausl Nov 22 '16 at 08:29
  • @codingwalebabu You should clarify your question ([edit] it), because as it currently is formulated, the answer to the linked question also answers this question. Maybe you need to explain better what you are trying to ask. – anatolyg Nov 22 '16 at 08:30
  • @tkausl , I asked what the significance of i<(1< – codingwalebabu Nov 22 '16 at 08:31

1 Answers1

1

In binary system, a power of 2 has a representation of 1 followed by zeros. For example:

25 = 32 (decimal) = 100000 (binary)

If you want to calculate a power of 2, shift a 1 several places left. The left-shift will fill the "new" places with zeros:

1 << 5 (C/Java notation) = 100000 (binary) = 32 (decimal) = 25

So you can use left-shift as an easy way to calculate a power of 2.


You cannot calculate a power of e.g. 3 as easily. For example, the following C code will calculate a power of 3:

(int)(pow(3.0, 5.0) + 0.5)

It needs conversion to int (or another suitable type) if you want to use it in as a loop termination condition. This conversion looks ugly and it's possible to get it wrong (if you omit the + 0.5).

So if you need a power of 2, and not any other number, it's easier to just use left-shift.

anatolyg
  • 26,506
  • 9
  • 60
  • 134