How to check if a given number is a power of two?

前端 未结 5 872
说谎
说谎 2020-12-01 16:23

The code below isn\'t working right for some inputs.

a, i = set(), 1
while i <= 10000:
    a.add(i)
    i <<=         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-01 16:40

    The bin builtin returns a string "0b1[01]?" (regex notation) for every strictly positive integer (if system memory suffices, that is), so that we can write the Boolean expression

    '1' not in bin(abs(n))[3:]
    

    that yields True for n that equals 0, 1 and 2**k.

    1 is 2**0 so it is unquestionably a power of two, but 0 is not, unless you take into account the limit of x=2**k for k → -∞. Under the second assumption we can write simply

    check0 = lambda n: '1' not in bin(abs(n))[3:]
    

    and under the first one (excluding 0)

    check1 = lambda n: '1' not in bin(abs(n))[3:] and n != 0
    

    Of course the solution here proposed is just one of the many possible ones that
    you can use to check if a number is a power of two... and for sure not the most
    efficient one but I'm posting it in the sake of completeness :-)

提交回复
热议问题