LeetCode231:Power of Two
来源:互联网 发布:域名注册批量查询 编辑:程序博客网 时间:2024/05/16 08:05
Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
这道题有好多种解法。
解法一
只想到了这种解法,就是统计1的个数。对于任何给定的数字,如果它的二进制表示中1的个数为1,即可以表示成 1<<i的形式,那么它是2的幂,否则就不是的了,通过统计二进制中1的个数就可以判断它是否是2的幂。但是最开始没有考虑负数,提交失败后才发现要考虑负数。
runtime:8ms
class Solution {public: bool isPowerOfTwo(int n) { if(n<0) return false; int count=0; int offset=1; for(int i=0;i<31;i++) { if(n&1<<i) count++; } return count==1; }};
解法二
解法二就比较奇妙了,充分利用到了一个数的二进制数中只有1个1,其余位都为0这个性质,就是一个数x和x-1的所有为做按位与会为0,比如x=8时
100
&011
000
最后只有1行代码。
runtime:8ms
bool isPowerOfTwo(int n) { return n>0&&!(n&(n-1)); }
解法三
第三种解法利用到了c++中bitset这个类,顺道看了下reference中关于bitset的说明。
思想和第一种是一样的,但是利用了C++本身提供的类来实现。
runtime:8ms
bool isPowerOfTwo(int n) { bitset<32> b(n); return n>0&&b.count()==1; }
0 0
- LeetCode231:Power of Two
- Leetcode231 Power of Two
- Leetcode231 Power of Two
- leetcode231: Power of Two
- LeetCode231 Power of Two
- LeetCode231——Power of Two
- leetcode231-Power of Two(判断一个整数n是否为2的方幂)
- Power of Two
- [LeetCode] Power of Two
- 【LeetCode】Power of Two
- Power of Two
- power of two
- [Leetcode]Power of Two
- Power of Two
- [leetCode] Power of Two
- Power of Two
- 231Power of Two
- leetcode --Power of Two
- HDOJ 5316 Magician 线段树
- &
- java获取配置文件路径
- poj3295 -- Tautology--构造法
- CSS3 transition的使用
- LeetCode231:Power of Two
- 用api函数打开串口,获取系统时间
- Vuforia SDK---- AR开发vuforia定价去水印
- MFC是设置ToolBar
- iOS 关于获取网络类型和运营商信息
- 各种TLE。。
- 介绍一种简便的ppt转pdf方法
- 摇动触发函数
- 关于int类型数据在内存中的高低位存储问题