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:
Example 2:
Example 3:
Constraints:
-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:
Solution 2:
Reference
Last updated
Was this helpful?