Check if a Number is Power of 2 or Not
EasyExactly one bit set
Problem
Return whether a positive integer is a power of two.
A power of two has exactly one 1 bit — n AND (n-1) wipes it to zero.
The idea
A power of two has a single 1 bit, so subtracting one flips that bit off and turns everything below it on. ANDing the two therefore gives zero for powers of two and non-zero for everything else.
The trick
- `n > 0 && (n & (n - 1)) == 0`.
- The positivity check matters: 0 passes the AND test but is not a power of two.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — 16 Values: 16.
1return n>0 and (n & (n-1))==0Input
- array
- [16]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- n = 8
- Output:
- true
- Explanation:
- 8 = 2^3, a single 1 bit.
Example 2
- Input:
- n = 6
- Output:
- false
- Explanation:
- 6 is 110 — more than one bit set.
Example 3
- Input:
- n = 1
- Output:
- true
- Explanation:
- 1 = 2^0.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.