标签:while tip integer oop signed nbsp bsp XA mat
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?
解法1,经典的数学解法:
class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 0: return False
        n = int(round(math.log(num, 4)))
        return 4**n == num
解法2,迭代:
class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num <= 0: return False
        while num >= 4:
            if num % 4 != 0:
                return False
            num = num / 4    
        return num == 1        
解法3,最牛叉,
class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        return num > 0 and (num & (num - 1)) == 0 and (num - 1) % 3 == 0                
 因为,4^n - 1 = C(n,1)*3 + C(n,2)*3^2 + C(n,3)*3^3 +.........+ C(n,n)*3^n
i.e     (4^n - 1)  =  3 * [ C(n,1) + C(n,2)*3 + C(n,3)*3^2 +.........+ C(n,n)*3^(n-1) ]
This implies that (4^n - 1)  is multiple of 3.
类似解法:
return n & (n-1) == 0 and n & 0xAAAAAAAA == 0
或者是:
class Solution(object):
    def isPowerOfFour(self, n):
        """
        :type num: int
        :rtype: bool
        """         
        #1, 100, 10000, 1000000, 100000000, ....
        #1, 100 | 10000 | 1000000 | 100000000, ... = 0101 0101 0101 0101 0101 0101 0101 0101
        return n > 0 and n & (n-1) == 0 and (n & 0x55555555 != 0)         
因为n & n-1 == 0 就可以确定只有1个1, so 只要保证1的位置在1,3,5,7,。。。。这些位置上就行。
标签:while tip integer oop signed nbsp bsp XA mat
原文地址:https://www.cnblogs.com/bonelee/p/9206525.html