問題描述
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?
補(bǔ)充說明:
給定一個32位的整數(shù)择示,判斷這個數(shù)是否為4的幾次冪。
方案分析
- 首先看到這個題目能想到的是如何判斷一個數(shù)是不是2的幾次冪牢裳。
- 先分析2的幾次冪的問題音诈,通常會采用位操作的方式:(num & (num -1)) == 0
- 分析是否是4的幾次冪灼舍,其實(shí)思想類似,但需要注意兩點(diǎn):
- 4的幾次冪關(guān)注的二進(jìn)制位為偶數(shù)位,如1,3,5,7...31(從0開始)——對應(yīng)的16進(jìn)制為0x55555555吨娜;
- 不能只局限關(guān)注偶數(shù)位的值麻顶,還需要借助2的幾次冪的問題確保其他位不為1.
python實(shí)現(xiàn)
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return (num > 0) and ((num & (num-1)) == 0) and ((num & 0x55555555) == num)