Coding problem · Easy · Basics
Power of Two
Easy Algorithms & data structures
Return true if n is a power of two: n = 2^k for some integer k >= 0.
Example 1
Input: n = 16 Output: true
Example 2
Input: n = 6 Output: false
Example 3
Input: n = 1 Output: true
Hints
Hint 1
Keep dividing by 2 while the number is even; a power of two ends at 1.
Hint 2
Bit trick: a power of two has exactly one 1 bit, so n & (n − 1) == 0 (for n > 0).
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(log n) · Space O(1)
Divide by 2 while even and check that you end at 1, or use n > 0 && (n & (n - 1)) === 0, which clears the lowest set bit.
Reference solution
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
def is_power_of_two(n: int) -> bool:
return n > 0 and n & (n - 1) == 0
<?php
function isPowerOfTwo(int $n): bool
{
return $n > 0 && ($n & ($n - 1)) === 0;
}
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy