Check if a number is power of 2This can be checked in just one line of code as follows: if (n & (n-1) == 0) return true;
Examples: n=4: n-1 = 3 n & n-1 = 0 (AND of 100 with 011) n=9: n-1 = 8 n & n-1 = 9 (AND of 1001 with 1000) n=16: n-1 = 15 n & n-1 = 0 (AND of 10000 with 01111) Explanation: This works because if a number is power of 2, then it has only one 1 in it's binary representation. Due to this, n-1 gives 1s at all places right of original 1s place. Since, original number had only one 1 and that is absent in n-1, the ANDing of the two always gives 0 |
Got a thought to share or found a
bug in the code?
We'd love to hear from you:
Name: | |
Email: | (Your email is not shared with anybody) |
Comment: |
Facebook comments: