lintcode-easy-O(1) Check Power of 2
2016-03-03 07:49
260 查看
Using O(1) time to check whether an integer n is a power of
For
For
这道题就是看一下这个int二进制各位上总共是否只有一个1,如果只有一个1则是2的n次方。但是要注意特殊情况,如果这个数是Integer.MIN_VALUE,也只有一位是1,但是这个数是负数,所以不是2的n次方。
2.
For
n=4, return
true;
For
n=5, return
false;
这道题就是看一下这个int二进制各位上总共是否只有一个1,如果只有一个1则是2的n次方。但是要注意特殊情况,如果这个数是Integer.MIN_VALUE,也只有一位是1,但是这个数是负数,所以不是2的n次方。
class Solution { /* * @param n: An integer * @return: True or false */ public boolean checkPowerOf2(int n) { // write your code here int count = 0; if(n == Integer.MIN_VALUE) return false; for(int i = 0; i < 32; i++){ if(((n >> i) & 1) == 1) count++; } return count == 1; } };
相关文章推荐
- hive窗口函数理解加实践
- lintcode-easy-Number of Islands
- 【bzoj2085】[Poi2010]Hamsters hash+倍增
- 国际情商12项
- iOS --- 两个NSIndexPath对象的正确比较方式
- 开源的部分人脸检测库
- swift之表格控件简单使用(UITableview)
- C/C++研发实习生要求
- js面向对象组件
- 参加Google for publisher北京会议记录
- [转]Torch是什么?
- lintcode-easy-Nth to Last Node in List Show result
- 链表中删除节点引发的思考!!!
- 欢迎使用CSDN-markdown编辑器
- Lua开发
- lintcode-easy-Minimum Subarray
- Chrome 控制台console的用法
- hdoj_1253
- 设置html页面不让浏览器缓存的方法
- lintcode-easy-Minimum Path Sum