Power of Four — Solution in Python, Java & C++
Power of Four solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Power of Four is an easy coding problem on math, bit manipulation and recursion, asked in Amazon, Microsoft, Adobe and Two Sigma interviews.
- Difficulty: Easy
- Topics: Math, Bit Manipulation, Recursion
- Asked at: Amazon, Microsoft, Adobe, Two Sigma
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an integer n, return true if it is a power of four — that is, if n == 4^x for some integer x >= 0.
Example 1
Input: n = 16
Output: true
Example 2
Input: n = 5
Output: false
Example 3
Input: n = 1
Output: true
Constraints
-2147483648 <= n <= 2147483647
Follow-up: Can you decide it without any loop or recursion?
Hints for Power of Four
Hint 1
A power of four is first of all a power of two: positive with exactly one set bit, which
n & (n - 1) == 0tests.Hint 2
Among powers of two, the powers of four are the ones whose single bit sits at an even position.
Hint 3
Mask with
0x55555555, which has all the even-position bits set.
How to solve Power of Four
A power of four is a power of two whose single bit sits at an even position; mask with 0x55555555.
Approach
- Require
n > 0andn & (n - 1) == 0. - Require
n & 0x55555555 != 0.
Why it works
4^x = 2^(2x), so the single set bit is at an even index; 0x55555555 has exactly the even-index bits set.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
(n - 1) % 3 == 0is the arithmetic alternative for the even-position test.
Reference solution
Python
def isPowerOfFour(n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0 and (n & 0x55555555) != 0Java
public static boolean isPowerOfFour(int n) {
return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) != 0;
}C++
bool isPowerOfFour(int n) {
return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) != 0;
}JavaScript
var isPowerOfFour = function(n) {
return n > 0 && (n & (n - 1)) === 0 && (n & 0x55555555) !== 0;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 337 math problems · the whole catalogue
Learn the technique: Bit Manipulation · Recursion