問(wèn)題描述
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ǔ)充說(shuō)明:
給定一個(gè)32位的整數(shù),判斷這個(gè)數(shù)是否為4的幾次冪。
方案分析
- 首先看到這個(gè)題目能想到的是如何判斷一個(gè)數(shù)是不是2的幾次冪。
- 先分析2的幾次冪的問(wèn)題,通常會(huì)采用位操作的方式:(num & (num -1)) == 0
- 分析是否是4的幾次冪,其實(shí)思想類似,但需要注意兩點(diǎn):
- 4的幾次冪關(guān)注的二進(jìn)制位為偶數(shù)位,如1,3,5,7...31(從0開(kāi)始)——對(duì)應(yīng)的16進(jìn)制為0x55555555;
- 不能只局限關(guān)注偶數(shù)位的值,還需要借助2的幾次冪的問(wèn)題確保其他位不為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)