Bits And The Power of Two
January 27th, 2007 by LorenzoSometimes it is useful to find out if a particular integer represents a power of two. You can find that out with a simple trick.
A power of two in binary is represented by a all zeros, except for a single one. For example 00010000 is a power of two (2^4).
In fact you can calculate the n-th power of 2 with:
int power2(int n) { return (1<
If you subtract one from a power of two, you obtain a number which binary representation is a sequence of ones. Example in binary:
00010000 - 1 = 00001111
If you take this number and perform a logical AND with the original power of two you obtain a flat zero!
Example:
00010000 &
00001111
———
00000000
If you have any other number that is not a power of two, this doesn’t work anymore and you’d never obtain a zero.
For example let’s take 18, which is not a power of two.
18 in binary is 00010010
00010010 - 1 = 0001000100010010 &
00010001 =
———
00010000
Another example. Let’s take 14 which is another number that is not a power of two:
14 in binary is 00001110
00001110 - 1 = 0000110100001101 &
00001110 =
———
00001100
In general you’ll find that the result of (X-1)&X always contains at least a one… unless X is a power of two! Cool!
For this simple reason you can find out if an integer is a power of two with something like:
boolean isPowerOf2(int x) { return ((x-1) & x)==0; }
Enjoy! ![]()
January 28th, 2007 at 11:36 am
What about:
return ( x & 1 ) == 0 ;
?
January 28th, 2007 at 3:57 pm
No. That would only tell you if a number x is divisible by 2. It would not tell you if x it is a power of 2.
While all powers of 2 are even, it is not true that all even numbers are also powers of 2.
For example 6 is divisible by 2, but it is not a power of 2.
January 29th, 2007 at 8:29 am
This is a famous MSFT interview question too.
“Write me a function that tests if a number is a power of 2…” This is good info to remember!
Keep on coding!
Dave
January 29th, 2007 at 10:58 am
I think there are two special cases that will cause isPowerOf2 to give a false positive: 0 and -MAXINT-1.
January 29th, 2007 at 12:06 pm
Has someone been interviewing with google?