【leetcode 简单】 第六十五题 2的幂

给定一个整数n,判断它是否为2的次方幂。

方法:2,4,8都是2的n次幂

        任何整数乘以2,都相当于向左移动了一位,而2的0次幂为1,所以2的n次幂就是1向左移动n位。这样,2的幂的特征就是二进制表示只有最高位为1,其他位均为0。二进制标下形式为:

       10    100    1000 

  减1后与自身进行按位与,如果结果为0,表示这个数是2的n次幂

  01    011    0111

  结果:

  10&01 = 0    100&011 = 0   1000&0111 = 0 

  

class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return (False if n<=0 else n&(n-1)==0)
原文地址:https://www.cnblogs.com/flashBoxer/p/9527443.html