[Tutor] Power of Two Function
visar.zejnullahu at gmail.com
Sat Sep 1 01:17:04 CEST 2012
2^n in binary is 10...0 (with n 0s), and 2^n - 1 is 11...1 (with n 1s). So
if you do bitwise and (&) to 2^n and 2^n-1 you get all 0s. That's why you
check if (num & (num - 1)) == 0.
On Sat, Sep 1, 2012 at 12:54 AM, Lazar <chaostorm at gmail.com> wrote:
> I'm fairly new to Python and still learning.
> Can someone please explain to me in what way the following function
> checks if a number is a power of two? Basically, the second line of
> code is what I can't really grasp:
> def is_power2(num):
> return num != 0 and ((num & (num - 1)) == 0)
> Thank you,
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor