How do you check if a no is power of 2 in python?

Bit Manipulations

One approach would be to use bit manipulations:

[n & [n-1] == 0] and n != 0

Explanation: every power of 2 has exactly 1 bit set to 1 [the bit in that number's log base-2 index]. So when subtracting 1 from it, that bit flips to 0 and all preceding bits flip to 1. That makes these 2 numbers the inverse of each other so when AND-ing them, we will get 0 as the result.

For example:

                    n = 8

decimal |   8 = 2**3   |  8 - 1 = 7   |   8 & 7 = 0
        |          ^   |              |
binary  |   1 0 0 0    |   0 1 1 1    |    1 0 0 0
        |   ^          |              |  & 0 1 1 1
index   |   3 2 1 0    |              |    -------
                                           0 0 0 0
-----------------------------------------------------
                    n = 5

decimal | 5 = 2**2 + 1 |  5 - 1 = 4   |   5 & 4 = 4
        |              |              |
binary  |    1 0 1     |    1 0 0     |    1 0 1
        |              |              |  & 1 0 0
index   |    2 1 0     |              |    ------
                                           1 0 0

So, in conclusion, whenever we subtract one from a number, AND the result with the number itself, and that becomes 0 - that number is a power of 2!

Of course, AND-ing anything with 0 will give 0, so we add the check for n != 0.

math functions

You could always use math functions, but notice that using them without care could cause incorrect results:

  • math.log[x[, base]] with base=2:

    import math
    
    math.log[n, 2].is_integer[]
    
  • math.log2[x]:

    math.log2[n].is_integer[]
    

Worth noting that for any n

Chủ Đề