Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

思路

可以通过循环或者递归的方法求出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
if (num <= 0):
return False
else:
while (num > 1):
if (num % 4 != 0):
return False
num = num / 4
return True

也可以利用位运算的方法。

1
2
3
4
5
6
7
4: 100
3: 011
4 & 3 = 0
16: 10000
15: 01111
16 & 15 = 0

得到一个判断条件

1
( (num-1) & num) == 0 and (num-1) % 3 == 0

如果满足这个判断条件,就是四的乘方了。