Power of Two

A positive power of two has exactly one set bit — `n & (n - 1) == 0`.

Easy
Time O(1) Space O(1)
LeetCode
2 min read
bit-manipulation math

Problem#

Return true iff n is a positive integer power of two.

Examples#

  • n=1true; n=16true.
  • n=3false; n=0false; n=-1false.

Constraints#

  • -2^31 <= n <= 2^31 - 1.

Approach#

A positive power of two has a single 1 bit. n & (n - 1) clears the lowest set bit; if the result is 0 and n > 0, it had exactly one set bit.

Solution#

Power of Two
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
};

Editorial#

n - 1 flips all bits below the lowest set bit of n and clears that bit’s value to 0 above. ANDing removes it; if the rest was zero, the original had a unique set bit. The n > 0 guard rejects 0 and negative numbers.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.