342. Power of Four
Easy
1533288Add to ListShare
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?
class Solution:
def isPowerOfFour(self, n: int) -> bool:
"""
解题思路:常规做法,如果n<=0,肯定不是;
接着不断判断取余除不除得尽
参考别人的思路:n小于等于0肯定不是的
首先判断是否是2的次方,即二进制位只有一个1,假设n是2的次方,
那么 n & (n-1) = 0, 是充分必要条件
那么判断是否是4的次方,即二进制位奇数位是1,且和上面一样,只有一个1
只有一个位置是1可用2的次方这个判断 n & (n-1) = 0
奇数位是1可用 32位的奇数位全为1的数去与,不为0即存在奇数位为1
"""
# if n <= 0:
# return False
# if n == 1:
# return True
# if n % 4 != 0:
# return False
# return self.isPowerOfFour(n / 4)
# sign = 0b01010101010101010101010101010101
# print(sign)
return n > 0 and not (n & (n - 1)) and n & 1431655765