Command Palette

Search for a command to run...

Problem 34.4 · Bit ManipulationEasy

Power of Two

What it teaches: A power of two has exactly one set bit.

Practise it on judges as “Power of Two”.

The problem

Return true if n is a power of two.

Example 1

Input: n = 16
Output: true

Example 2

Input: n = 3
Output: false

Constraints

  • −2³¹ ≤ n ≤ 2³¹ − 1

Pattern clues in the wording

  • → Power of two check

These clues point to Bit Manipulation: Use XOR, AND, OR and shifts to test, set and cancel bits, often in O(1) space.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public boolean isPowerOfTwo(int n) {
        return false;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
n = 1
true
2
n = 16
true
3
n = 3
false

+ 2 hidden tests the code runner will check

From slow to fast

Approaches

1

One set bit

Time O(1) Space O(1)

Positive and clearing the lowest bit leaves 0.

Approach 1
class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
}

Verdict: No loops.

Before you submit

Edge cases and common mistakes

Test these inputs

  • 0 (false)
  • Negative numbers (false)
  • Integer.MIN_VALUE (one set bit, but negative)

Mistakes people make

  • Forgetting n > 0 (MIN_VALUE passes the bit test).

Interview

Follow-up questions

Power of four?