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