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 == 4^x.
Q: What is the range of the integer n?
A: The integer n will be within the typical 32-bit signed integer range, i.e., from -2^31 to 2^31 - 1.
Q: Is 1 considered a power of four?
A: Yes, 1 is 4^0, so it should return true.
Q: How should negative numbers be handled?
A: Negative numbers will never be a power of four, so they should return false.
To determine if a number is a power of four, we can use the following criteria:
3.1 is 0001, 2 is 0010, 4 is 0100, etc. To check if a number n is a power of two, the condition (n & (n - 1)) == 0 must hold true.4^0 = 1, 4^1 = 4, 4^2 = 16, etc.). Therefore, if a number n is a power of four, then (n - 1) % 3 == 0 is also true because of properties of power of four in modulus arithmetic.class Solution {
public:
bool isPowerOfFour(int n) {
// Check if n is positive
if (n <= 0) return false;
// Check if n is a power of two
if ((n & (n - 1)) != 0) return false;
// Check if n - 1 is divisible by 3
return (n - 1) % 3 == 0;
}
};
This solution efficiently checks if a number is a power of four using bitwise operations and modulus arithmetic, both of which are very efficient.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?