1
One set bit
Time O(1) Space O(1)Positive and clearing the lowest bit leaves 0.
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}Verdict: No loops.
Search for a command to run...
What it teaches: A power of two has exactly one set bit.
Practise it on judges as “Power of Two”.
Return true if n is a power of two.
Example 1
Input: n = 16 Output: true
Example 2
Input: n = 3 Output: false
Constraints
Pattern clues in the wording
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
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
| # | Input | Expected |
|---|---|---|
| 1 | n = 1 | true |
| 2 | n = 16 | true |
| 3 | n = 3 | false |
+ 2 hidden tests the code runner will check
From slow to fast
Positive and clearing the lowest bit leaves 0.
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}Verdict: No loops.
Before you submit
Test these inputs
Mistakes people make
Interview
Power of four?