【LEETCODE】231-Power of Two

来源:互联网 发布:ubuntu下安装win10 编辑:程序博客网 时间:2024/06/14 06:38

Given an integer, write a function to determine if it is a power of two.


题意:

给一个整数,写一个函数判断它是否是2的幂


参考:

http://bookshadow.com/weblog/2015/07/06/leetcode-power-of-two/


思路:

如果一个整数是2的幂,那么它的二进制形式最高位为1,其余各位为0
等价于:n & (n - 1) = 0,且n > 0




class Solution(object):    def isPowerOfTwo(self, n):        """        :type n: int        :rtype: bool        """                return n>0 and n&(n-1)==0


0 0