website/content.en/ChapterFour/0300~0399/0342.Power-of-Four.md
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Follow up: Could you solve it without loops/recursion?
Given an integer (signed 32 bits), write a function to determine whether it is a power of 4.
(4^n - 1) % 3 == 0: (1) 4^n - 1 = (2^n + 1) * (2^n - 1) (2) Among any 3 consecutive numbers (2^n-1), (2^n), (2^n+1), there must be one number that is a multiple of 3. (2^n) is definitely not a multiple of 3, so either (2^n-1) or (2^n+1) must be a multiple of 3. Therefore, 4^n-1 must be a multiple of 3.
package leetcode
// Solution 1: Number theory
func isPowerOfFour(num int) bool {
return num > 0 && (num&(num-1)) == 0 && (num-1)%3 == 0
}
// Solution 2: Loop
func isPowerOfFour1(num int) bool {
for num >= 4 {
if num%4 == 0 {
num = num / 4
} else {
return false
}
}
return num == 1
}