Power of Two
Easy
Topics
Given an integer n, return true if it is a power of two (i.e., n == 2^x for some non-negative integer x).
Example 1
A power of two has exactly one set bit, so
n-1 flips every bit below it and n & (n-1) comes out zero. Here it is 0, so the answer is true.Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input: n = 1 Output: true
Example 2
Input: n = 16 Output: true
Example 3
Input: n = 3 Output: false
Constraints
- -2^31 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
A positive power of two has exactly one bit set. Subtracting 1 from such a number flips that bit to 0 and sets every bit below it, so the two values share no bits at all and n & (n - 1) is 0.
n = 8 = 1000
n - 1 = 7 = 0111
AND = 0000 exactly one bit was set
n = 6 = 0110
n - 1 = 5 = 0101
AND = 0100 more than one bit setThe n > 0 guard is not optional. Zero gives 0 & -1 == 0 and would pass; negatives in two's complement also slip through. So the test is the conjunction.
Approach
- Return
n > 0 and (n & (n - 1)) == 0.
Dry Run
n = 1 positive, 1 & 0 = 0 -> true
n = 16 positive, 16 & 15 = 0 -> true
n = 3 positive, 3 & 2 = 2 -> false
n = 0 fails the n > 0 guard -> false
n = -16 fails the n > 0 guard -> false
(without it, -16 & -17 == -32, non-zero, so it would
happen to return false anyway -- but 0 would not)Complexity
- Time — O(1): two operations, against O(log n) for repeated division.
- Space — O(1).
Common Pitfalls
- Dropping the positivity check, which lets 0 through.
- Using
n % 2 == 0as the test, which accepts any even number. - Using
log2(n)and testing for an integer result. Floating point makes large powers land just off, so it is both slower and less reliable. - Counting set bits with popcount and comparing to 1. Correct and equally fast, and arguably clearer — but still needs the positivity guard.
Full Solution — all languages
class Solution:
def isPowerOfTwo(self, n):
return n > 0 and (n & (n - 1)) == 0import java.util.*;
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
};/**
* @param {number} n
* @return {boolean}
*/ var isPowerOfTwo = function(n) {
return n > 0 && (n & (n - 1)) === 0;
};
Asked at
Qualcomm