231 Power of Two

原问题链接: https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.

参考别人的回答如下:
这两个回答的基本思路是2的n次方在转换为二进制表示时只有一个1,所以将n用二进制表示并数一下转换后数字里1的个数就可以了。

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <=0:
            return False
        #use bin() to convert n into binary number
        return bin(n).count('1') == 1
def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        counts = 0
        if n>0:
            while n!=0:
                counts += n&1
                #>> is bitwise operator
                n>>=1
        return counts==1

相关bitwise文档:
https://wiki.python.org/moin/BitwiseOperators

The Operators:
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2
y.
x & y
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
x | y
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
~ x
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
x ^ y
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,872评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,992评论 3 20
  • 1.有本事的领导培养人;没本事的领导祸害人 有本事的领导会培养下属,想办法让下属能够独当一面,所谓众人拾柴火焰高,...
    一条狗的流浪记阅读 187评论 0 0
  • 工作久了,你会发现有很多问题不是什么特别的难,都是一些很简单的细节导致的,就好比某种东西你以为是约定俗成的,不用说...
    _源汐_阅读 122评论 0 0
  • 满眼的春色
    求败熊阅读 125评论 0 0

友情链接更多精彩内容