Given an integer n, return true if it is a power of two, otherwise return false. An integer n is a power of two if there exists an integer x such that n == 2ˣ.
n = 1truen = 16truen = 3falseA power of 2 like 8 (1000) has exactly one set bit. Subtracting 1 gives 7 (0111) — all bits below the set bit flip to 1, and the set bit itself becomes 0. The AND of 8 & 7 = 0. For any number that is not a power of 2, like 6 (110), subtracting 1 gives 5 (101). The AND 6 & 5 = 4 ≠ 0, so the check fails. The extra n > 0 guard handles 0 and negatives, since 0 & −1 would otherwise give 0 incorrectly.
You can keep dividing by 2 while the number is even, and check if you reach 1. That takes O(log n) steps.
In binary, a power of two has exactly one 1 bit. Removing the lowest set bit, with n AND n −1, leaves 0 only in that case. Also require n to be positive, because 0 and negative numbers are not powers of two.
A power of two has exactly one set bit. n greater than 0 and n AND n −1 equal to 0.
Run the animation above on your own input, or watch the 1:29 video explanation of Power of Two with a dry run and Java code.