zoukankan      html  css  js  c++  java
  • 算法——求幂

    求幂

    二的幂次方都有一个特点,这些数字的二进制数都只会出现一个1,跟着几个0。

    而四的幂次方则相似,不过它们的二进制数中0只会出现偶数次、而不是奇数次。

    # power_exponent.py 求幂
    from math import pow
    
    class Solution:
        def is_power_of_two(self, n: int) -> bool:
            if n <= 0:
                return False
            if bin(n)[2:].count('1') == 1:
                return True
            return False
    
        def is_power_of_four(self, n: int) -> bool:
            if n <= 0:
                return False
            s = bin(n)[2:]
            if s.count('1') == 1 and s.count('0') % 2 == 0:
                return True
            return False
    
    def test():
        solution = Solution()
        l = [int(pow(2, i)) for i in range(10)]
        #l = [i for i in range(100)]
        for i in l:
            print(i, bin(i))
            print('is_power_of_two: ', solution.is_power_of_two(i))
            print('is_power_of_four: ', solution.is_power_of_four(i))
    
    if __name__ == '__main__':
        test()
    Resistance is Futile!
  • 相关阅读:
    爬虫大作业
    熟悉常用的HDFS操作
    数据结构化和保存
    爬取全部校园新闻
    爬取校园新闻
    Google布隆过滤器
    谷歌json和对象转换
    postgresql和postgis
    json和实体类互相转换
    Linux安装docker-compose
  • 原文地址:https://www.cnblogs.com/noonjuan/p/11102618.html
Copyright © 2011-2022 走看看