原題
給出一個整數(shù) (32 位), 寫出一個函數(shù)判斷它是不是4的次方數(shù)
樣例:
給出 num = 16, 返回 true.
給出 num = 5, 返回 false.
解題思路
- 如果一個數(shù)是4的次方數(shù)要滿足兩點
- 第一:這個數(shù)一定是2的次方數(shù) => num & (num - 1) == 0
- 第二: 二進制中0的個數(shù)是偶數(shù)個,比如4的二進制是100
因為滿足第一條别惦,所以這個數(shù)的二進制一定是1后面跟幾個0脚猾,為了保證0為偶數(shù)個缩焦,總體長度應(yīng)為奇數(shù)個
完整代碼
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return num > 0 and num & (num - 1) == 0 and len("{0:b}".format(num)) % 2 == 1