码迷,mamicode.com
首页 > 编程语言 > 详细

python leetcode 日记--231. Power of Two

时间:2016-05-07 19:41:16      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

class Solution(object):
    def isPowerOfTwo(self, n):
        #
        """
        :type n: int
        :rtype: bool
        """


方法:分析2的幂次方的特点,发现2的任意次方的数,化成二进制时只有首位为1其余位为0,因此我的解决方法如下:

class Solution(object):
    def isPowerOfTwo(self, n):
        return False if n<0 else (True if bin(n).count(1)==1 else False)

bin函数能将一个给定的数化成二进制,返回为字符串形式,因此只要检查bin的返回值中是否含有一个‘1’即可。

将上面的一行代码分解来看就是

class Solution(object):
    def isPowerOfTwo(self, n):
        if n<0:
            return False
        return True if bin(n).count(1)==1 else False


之后看其中其他解决方法主要为n&(n-1)==0,这个方法也是利用了2的幂次方的特点,n若是2的幂次方,那么(n-1)的二进制数只有最高位为0,其余位全为1,因此让n&(n-1)按位与,如果等于0,则说明n是2的幂次方

 

python leetcode 日记--231. Power of Two

标签:

原文地址:http://www.cnblogs.com/aksdenjoy/p/5468934.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!