• leetcode 342. Power of Four


    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,。。。。这些位置上就行。

  • 相关阅读:
    书摘--可能与不可能的边界
    电影-茶室
    使用unittest,if __name__ == '__main__':里代码不执行的解决办法
    Pycharm中配置鼠标悬停快速提示方法参数
    Python 解决pip使用超时的问题
    Linux性能监控命令——sar详解
    Linux系统管理
    Linux top命令的用法详细详解
    CentOs7排查CPU高占用
    centos 7 查看磁盘io ,找出占用io读写很高的进程
  • 原文地址:https://www.cnblogs.com/bonelee/p/9206525.html
Copyright © 2020-2023  润新知