zoukankan      html  css  js  c++  java
  • 【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)
    
  • 相关阅读:
    HDU 5650 异或
    HDU 5646
    HDU 5645
    P2075 [NOIP2012T5]借教室 区间更新+二分查找
    HDU 5641
    读写分离
    linux执行cmd之一
    html2image
    挂载引起的权限问题
    如何防止sql注入
  • 原文地址:https://www.cnblogs.com/flashBoxer/p/9527443.html
Copyright © 2011-2022 走看看