Maintained by Vikas Dulgunde, software engineer
You receive a single integer n. Your job is to report whether n can be written as 2 raised to a non-negative whole power: 1, 2, 4, 8, 16, and so on. If such an exponent exists, return true; if not, return false.
Note that 1 counts as a power of two because it equals 2 to the zero. Zero and every negative number can never be a power of two, so those must always return false.
The input can be any 32-bit signed integer, which means it ranges from a large negative value up to a large positive one. A correct answer has to handle the edge cases at both ends, not just the small friendly numbers.
The fastest known approach hinges on how powers of two look in binary: each one has a single 1 bit and nothing else set, which gives a constant-time check.
1 equals 2 to the zero, so it is a power of two.
16 equals 2 to the fourth. In binary it is 10000, a single set bit.
3 is 11 in binary, which has two set bits, so it sits between 2 and 4 rather than on a power.
A power of two is always positive, so any negative input returns false even though 4 itself is a power of two.
Visible test cases
Powers of two are always strictly positive, so you can reject zero and every negative number up front.
Write a few powers of two in binary (1, 10, 100, 1000) and count the 1 bits in each. Notice they all have exactly one.
For a number with one set bit, subtracting 1 flips that bit to 0 and turns every lower bit to 1, so n and n-1 share no bits. Test that with a bitwise AND.
Keep dividing by 2 while the value stays even; a true power of two reduces all the way down to 1.
A positive power of two has exactly one set bit, and for such numbers n & (n - 1) clears that bit and yields 0.