#342
Power of Four
EasyMathBit ManipulationRecursionBit ManipulationMathematical Properties
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(log n) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
We can use a mathematical property of powers of four. A number is a power of four if it is a power of two and the exponent is even. We can check this using bit manipulation.
⚙️
Algorithm
3 steps- 1Step 1: Check if n is greater than 0.
- 2Step 2: Check if n is a power of two by ensuring only one bit is set (n & (n - 1) == 0).
- 3Step 3: Check if the set bit is in the correct position for powers of four using (n - 1) % 3 == 0.
solution.py2 lines
1def isPowerOfFour(n):
2 return n > 0 and (n & (n - 1)) == 0 and (n - 1) % 3 == 0ℹ
Complexity note: The time complexity is O(1) because we are performing a constant number of operations regardless of the input size.
- 1A number must be positive to be a power of four.
- 2Using bit manipulation can simplify checks for powers of two.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.