Skip to content
Problem 231 · LeetCode 231(opens in a new tab)

Power of Two

EasyBit manipulation

You are given a whole number n. Decide whether it equals 2 raised to some whole power k ≥ 0, that is one of 1, 2, 4, 8, 16 and so on.

Return true if it does and false otherwise. Zero and negative numbers are never powers of two.

Example 1

Input:  n = 64
Output: true
Why:    64 = 2 × 2 × 2 × 2 × 2 × 2
2 more examples and the constraints

Example 2

Input:  n = 12
Output: false
Why:    12 = 4 × 3, and 3 is odd

Example 3

Input:  n = -16
Output: false
Why:    a power of two is always positive

Constraints

  • −2,147,483,648 ≤ n ≤ 2,147,483,647 (any 32-bit signed integer)
  • Follow-up: answer without a loop or recursion

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Keep halvingO(log n)
  2. Count the set bitsO(1)
  3. n & (n − 1)O(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 1,073,741,824Verdict
Keep halvingO(log n)
Passes; uses a loop
Count the set bitsO(1)
Passes; needs a built-in
n & (n − 1)O(1)
Best; one expression

n = the input number; log n is at most 31 here.

Edge cases to test

  • Zero. 0 & (0 − 1) is 0, so without the n > 0 check, 0 would pass.
  • One. 1 is 2 to the power 0, so it must return true.
  • Negative numbers. -16 and the smallest int, -2,147,483,648, are both false.
  • Largest power that fits. 1,073,741,824 (2 to the 30) is true; 2,147,483,647 is not.

Common mistakes

  • Dropping the n > 0 check, so 0 and the smallest int come back true.
  • Writing n & n - 1 == 0 in Java, C++ or TypeScript: == binds tighter than &, so the parentheses are needed.
  • Testing whether log2(n) is a whole number in floating point, which can round wrong near large powers.

How to talk through it

  1. 1Clarify. Can n be zero or negative? Is 1 a power of two? (Yes: 2 to the 0.)
  2. 2Start with halving. Divide by 2 while even and check for 1; say it is O(log n), at most 31 steps.
  3. 3Think in binary. A power of two is a single 1 bit followed by 0s.
  4. 4Use the bit trick. n & (n − 1) clears the lowest set bit; zero left means there was only one.
  5. 5Test out loud. Run 0, 1, a negative number and 2 to the 30 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?