Power of Four
EASYDescription
Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4x.
Example 1:
Input: n = 16 Output: true
Example 2:
Input: n = 5 Output: false
Example 3:
Input: n = 1 Output: true
Constraints:
-231 <= n <= 231 - 1
Follow up: Could you solve it without loops/recursion?
Approaches
Checkout 4 different approaches to solve Power of Four. Click on different approaches to view the approach and algorithm in detail.
Iterative Approach
This approach uses a loop to check if the given number n is a power of four. We start with a variable, say powerOfFour, initialized to 1. We repeatedly multiply this variable by 4 in a loop. If powerOfFour becomes equal to n at any point, we've found that n is a power of four. If powerOfFour exceeds n, it means n cannot be a power of four, as we've passed the potential value.
Algorithm
- Handle the edge case: If
nis less than or equal to 0, it cannot be a power of four, so returnfalse. - Initialize a long variable
powerOfFourto 1. We uselongto prevent overflow whenpowerOfFour * 4exceedsInteger.MAX_VALUE. - Start a
whileloop that continues as long aspowerOfFouris less thann. - Inside the loop, update
powerOfFourby multiplying it by 4 (powerOfFour *= 4). - After the loop, check if
powerOfFouris equal ton. If they are equal,nis a power of four. Otherwise, it is not.
The core idea is to generate powers of four one by one and compare them with the input number n. We start with 4^0 = 1. In each step of a loop, we multiply our current number by 4 to get the next power of four. We stop when our generated number is greater than or equal to the input n. Finally, we check if our number is exactly equal to n.
class Solution {
public boolean isPowerOfFour(int n) {
if (n <= 0) {
return false;
}
long powerOfFour = 1;
while (powerOfFour < n) {
powerOfFour *= 4;
}
return powerOfFour == n;
}
}
Complexity Analysis
Pros and Cons
- Simple to understand and implement.
- Works correctly for all valid integer inputs.
- Less efficient than constant-time solutions.
- Does not satisfy the follow-up constraint of solving the problem without loops or recursion.
Code Solutions
Checking out 4 solutions in different languages for Power of Four. Click on different languages to view the code.
class Solution {
public
boolean isPowerOfFour(int n) {
return n > 0 && (n & (n - 1)) == 0 && (n & 0xaaaaaaaa) == 0;
}
}
Video Solution
Watch the video walkthrough for Power of Four
Similar Questions
5 related questions you might find useful
Patterns:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.