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

前端 未结 5 870
说谎
说谎 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:35

    Refer to the excellent and detailed answer to "How to check if a number is a power of 2" — for C#. The equivalent Python implementation, also using the "bitwise and" operator &, is this:

    def is_power_of_two(n):
        return (n != 0) and (n & (n-1) == 0)
    

    As Python has arbitrary-precision integers, this works for any integer n as long as it fits into memory.

    To summarize briefly the answer cited above: The first term, before the logical and operator, simply checks if n isn't 0 — and hence not a power of 2. The second term checks if it's a power of 2 by making sure that all bits after that bitwise & operation are 0. The bitwise operation is designed to be only True for powers of 2 — with one exception: if n (and thus all of its bits) were 0 to begin with.

    To add to this: As the logical and "short-circuits" the evaluation of the two terms, it would be more efficient to reverse their order if, in a particular use case, it is less likely that a given n be 0 than it being a power of 2.

提交回复
热议问题