sagelearnai

Power of Two

Difficulty: Easy · Pattern: Bit Manipulation · LeetCode #231

Return true if n is a power of two (n == 2^x for some integer x ≥ 0).

Examples

text
1 → true    16 → true    3 → false    0 → false    -16 → false

Hints

  1. A power of two has exactly one set bit.
  2. n & (n − 1) clears the lowest set bit.

Approach

n > 0 and (n & (n − 1)) == 0. Subtracting 1 flips the lowest set bit and every zero below it, so the AND clears that bit. If nothing remains, there was only one bit.

The n > 0 guard rules out 0 and negative numbers (in two's complement, INT_MIN has a single set bit too). This identity is the basis of Brian Kernighan's popcount loop.

Complexity

Time: O(1). Space: O(1).

Python solution
def isPowerOfTwo(n):
    return n > 0 and n & (n - 1) == 0
JavaScript solution
function isPowerOfTwo(n) {
  return n > 0 && (n & (n - 1)) === 0;
}