LeetCode之Power of Two
来源:互联网 发布:软件开发思路 编辑:程序博客网 时间:2024/05/16 10:54
1、题目
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.
Subscribe to see which companies asked this question.
2、分析
比如我们发现1、2、4、8、16转化成二进制为
1、10、100、1000、10000、
我们发现第一位是1后面都是0
思路1、
我们先把这个数字和1进行&操作得到一个数temp,然后原数右移动,然后把右移的数字再和1进行&操作,然后和temp相加,如果都是1000,temp之元数不是1之前都是0,最后一次右移动,就成了1,temp == 1,就可以了返回是
思路2、
我们原素减去-1和元素&操作,如果结果为0就说明是。
3、代码实现
C++代码实现1
class Solution {public: bool isPowerOfTwo(int n) { int temp = 0; while (n > 0) { temp += (n & 1); n >>= 1; } return temp == 1; }};
C++代码实现2
class Solution {public: bool isPowerOfTwo(int n) { return (n > 0) && !(n & (n - 1)); }};
java代码实现2
public class Solution { public boolean isPowerOfTwo(int n) { return (n > 0) && ((n & (n - 1)) == 0 ? true : false); }}
0 0
- LeetCode之Power of Two
- leetcode 之 power of two
- leetcode之Power of Two
- leetcode之Power of Two
- LeetCode之Power of Two
- [LeetCode] Power of Two
- 【LeetCode】Power of Two
- [Leetcode]Power of Two
- [leetCode] Power of Two
- leetcode --Power of Two
- leetcode: Power of Two
- LeetCode Power of Two
- [LeetCode] Power of Two
- LeetCode Power of Two
- [leetcode] Power of Two
- [Leetcode]Power of Two
- Leetcode: Power of Two
- [LeetCode]Power of Two
- 通过IP地址获得用户所在城市的额天气信息的整理
- ViewPager+Fragment实现
- Spring学习之SpEL(一)
- 初学者(一)欢迎大家指点
- 141. Linked List Cycle
- LeetCode之Power of Two
- 从农村放牛娃到清华博士:不那么“聪明”的他如何一路逆袭?
- Real-Time Direct Dense Matching on Fisheye Images
- 浏览器兼容性杂谈
- c知识点总结大全
- [MongoDB]MongoDB学习
- 语义分析的一些方法(一)
- [计算机视觉][ARM-Linux开发] Ubuntu14.04安装OpenCV3.2中遇到的问题的解决方案
- 关于hibernate 里面的序列