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
相关文章推荐
- python的学习笔记
- Python处理Excel(三):内置数据类型处理Excel数据
- python 中的赋值、引用、拷贝、作用域
- python第二站续--字典dict
- python代码结构
- python {File "<stdin>", line 1} error
- py2exe打包Python程序
- python2.7安装matplotlib的一些问题
- Visual Studio Build Events 使用脚本python
- python爬虫之-BeautifulSoup
- python---------列表和元组
- Python OpenCV中色彩空间的转换类型
- Python学习笔记:列表(list)基本内容
- Python xrange与range的区别
- 204. Count Primes [easy] (Python)
- 奇怪的Python本地线程Python's Thread Locals Are Weird
- Python 的闭包和装饰器
- 如何过渡至 Python 3
- Python 阅读书目推荐
- Python 内部:可调用对象是如何工作的