342. Power of Four
LeetCode 342. Power of Four
Description
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.
Example 1:
Input: n = 16
Output: trueExample 2:
Input: n = 5
Output: falseExample 3:
Input: n = 1
Output: trueConstraints:
-2^31 <= n <= 2^31 - 1
Follow up: Could you solve it without loops/recursion?
Tags
Bit Manipulation
Solution
From LeetCode 231. Power of Two we know that a positive number n is a power of 2 when n&(n-1) == 0. We also know if a positive number n is a power of 4, it must a power of 2. Therefore, we can start off the characteristics of n = 4^x.
Such numbers represented in binary are like 1, 100, 10000, ... . We can find that 1 appears at odd-bits. Thus, we can use a number whose even-bits are all filled with 1 and use it to test with
n;4^x % 3 == 1.
We can derive 2 statements from both characteristics, and append either of them to the solution of Power of Two.
n&0xaaaaaaaa == 0;n%3 == 1.
Complexity
Time complexity:
Space complexity:
Code
Solution 1:
func isPowerOfFour(n int) bool {
return n > 0 && n&(n-1) == 0 && n%3 == 1
}Solution 2:
func isPowerOfFour(n int) bool {
return n > 0 && n&(n-1) == 0 && n&0xaaaaaaaa == 0
}Reference
Last updated
Was this helpful?