题目描述
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
给定一个整数(带符号的32位),写一个函数来检查它是否为4的幂。
Example 1:
Input: 16
Output: true
Example 2:
Input: 5
Output: false
Python Solution
**分析:**由题目易得知 4 的幂一定是 2 的幂,所以在上一篇LeetCod*231 Power of Two的基础上对代码进行改动。
solution 1
继续进行位运算,利用0x55555555来和自身做 & 运算并和自身作对比。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0 and (n & 0x55555555) == n
solution 2
在之前的基础上观察 4 的幂转化为二进制后, 0 的个数都为偶数个,所以加个判断条件就好。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and bin(n).count('1‘) == 1 and bin(n).count('0') % 2 == 1
还没完还没完,接下来:
炫技时刻
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0 and (n - 1) % 3 == 0
其实也还好,就是思维要绕个弯,数学归纳法即可证得。