question
Write a function to determine if a number is a power of two.
For this question really think outside of the box. Try to think in terms of lower level code.
At first thought you may decide to use a recursive function or a while loop. Both of
these though are bested by simply using the binary representation of the numbers. In
fact, the solution runs in O(1).
Any number that is a power of two will have one bit in its binary form.
ex.
Subtracting 1 from the powers will result in the following binary representations:
Using a bitwise '&' operator to compare the original power number and the number subtracted by one will result in 0.
ex.
This unique pattern will only work if the input number is a power of two.
Note: This trick was actually very popular in the past but seems to be new to many recent grads. If you're having trouble with bitwise operators check out this site.
Any number that is a power of two will have one bit in its binary form.
ex.
2 = 00010
4 = 00100
8 = 01000
16 = 10000
Subtracting 1 from the powers will result in the following binary representations:
2 - 1 = 1 = 00001
4 - 1 = 3 = 00011
8 - 1 = 7 = 00111
16 - 1 = 15 = 01111
Using a bitwise '&' operator to compare the original power number and the number subtracted by one will result in 0.
ex.
00010 & 00001 = 0
This unique pattern will only work if the input number is a power of two.
isPowerOfTwo(int input)
return (input != 0) && (input & (input - 1)) == 0;
Note: This trick was actually very popular in the past but seems to be new to many recent grads. If you're having trouble with bitwise operators check out this site.