231. Power of Two [easy] (Python)
来源:互联网 发布:淘宝重复开店2017处罚 编辑:程序博客网 时间:2024/06/07 05:08
题目链接
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,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51322908
0 0
- 231. Power of Two [easy] (Python)
- LeetCode 231. Power of Two --Easy
- Easy-题目22:231. Power of Two
- Leetcode 231. Power of Two (Easy) (cpp)
- 231. Power of Two python
- 【leetcode】Power Of Two[easy]
- Leet Code OJ 231. Power of Two [Difficulty: Easy]
- [leetcode: Python]231. Power of Two
- [Leetcode 231, Easy] Power of Two
- 【LeetCode】(231)Power of Two(Easy)
- <LeetCode><Easy>231 Power of Two
- LeetCode #231 - Power of Two - Easy
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 【真枪实干系列】Xibo-CMS-Layout关于时间轴优先级的测试
- android--UI相关常用类简介
- 数据库--完整性
- View滑动
- MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合
- 231. Power of Two [easy] (Python)
- D26
- java中22种设计模式
- Spark生态之Alluxio学习4---下载源码通过maven install安装失败记录
- 欢迎使用CSDN-markdown编辑器
- 获取一个数据库中的Table
- 黑客短教程
- 网络仿真工具TOTEM之——IP路由功能
- busybox_httpd, http, CGI