Just out of curiosity, how can you tell if a number x is a power of two (x = 2^n) without using recursion.
Thanks
Best Answer
One way is to use bitwise AND. If a number $x is a power of two (e.g., 8=1000), it will have no bits in common with its predecessor (7=0111). So you can write:
($x & ($x - 1)) == 0
Note: This will give a false positive for $x == 0.
You need refresh yourself on how binary works. 5 is not represented as 0001 1111 (5 bits on), it's represented as 0000 0101 (2^2 + 2^0), and 4 is likewise not 0000 1111 (4 bits on) but rather 0000 0100 (2^2). The numbers you wrote are actually in unary.
Now, if nisn't a power of 2, then its binary representation will have some other 1s in addition to the leading 1, which means that both n and n - 1 will have the same leading 1 bit (since subtracting 1 cannot possibly turn off this bit if there is another 1 in the binary representation somewhere). Hence the & operation cannot produce 0 if n is not a power of 2, since &ing the two leading bits of n and n - 1 will produce 1 in and of itself. This of course assumes that n is positive.
Best Answer
One way is to use bitwise AND. If a number
$x
is a power of two (e.g., 8=1000), it will have no bits in common with its predecessor (7=0111). So you can write:Note: This will give a false positive for $x == 0.