python1
leetcode上面的很简单的题目
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?
python解决方案:
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
while num > 0 and num & 3 == 0:
num >>= 2
return num == 1
题解:
如果是4的倍数,表示成二进制的话
4 100
16 10000
64 1000000
就是这种形式
所以代码的思路就是
整型的num
每回判断它的后两位是不是0 (也即和3相与结果是不是0)
然后num=num/4 (即右移两位)
判断最后剩下的是不是一。