您的位置:首页 > 编程语言 > Python开发

231. Power of Two [easy] (Python)

2016-05-05 14:47 791 查看

题目链接

https://leetcode.com/problems/power-of-two/

题目原文

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

题目翻译

给定一个整数,写一个函数判断它是否是2的若干次幂。

思路方法

思路一

比较直观暴力的想法是,如果每次将这个数除以2没有余数,直到得到数字1,那么这个数就是2的若干次幂。

代码

class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 1:
return False
while n%2 == 0:
n /= 2
return True if n==1 else False


说明

当然,除以2是比较特殊的除法,所以也可以通过移位实现上面的除法。

思路二

注意到2的幂次
x
表示成二进制一定是一个1后面若干个0,那么只要计算输入数的二进制表示是否只有一个1即可。

代码

class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and bin(n).count('1') == 1


思路三

类似思路二,2的幂次
x
表示成二进制一定是一个1后面若干个0,那么
x-1
一定是一个0后面若干个1,所以
x & (x-1) = 0
,非2的幂无法得到0。

代码

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


PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!

转载请注明:/article/11857815.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: