Leetcode: Power of Two
2015-12-20 04:28
162 查看
Given an integer, write a function to determine if it is a power of two.
还是有一个地方不小心:Integer.MIN_VALUE, 应该是false,但是因为只有一个1,我曾经判断为true。事实上,所有negative value都应该是false
better method: 一旦符号位为1,就return false, 检查其他位只有1个1
public class Solution { public boolean isPowerOfTwo(int n) { boolean one = false; for (int i=0; i<32; i++) { if (((n>>i) & 1) == 1) { if (i == 31) return false; if (!one) one = true; else return false; } } return one; } }
做的时候遇到很多语法错误:
1. “==” 优先级 比 “&” 高, “&”表达式一定要括起来
2. >>是带符号的右移,如果是负数,高位始终补1. >>>才是无符号的右移
这样也可以,先确认除开符号位的31位只有一个1,然后确认符号位不为1,注意一定要无符号右移,或者写成 ((n>>31)&1) != 1
public class Solution { public boolean isPowerOfTwo(int n) { boolean one = false; for (int i=0; i<31; i++) { if (((n>>i) & 1) == 1) { if (!one) one=true; else return false; } } return one && (n>>>31)!=1; } }
相关文章推荐
- 【jQuery】cookie插件——cookie
- 特别码字3
- 【jQuery】图片放大镜插件——jqzoom
- 特别码字2
- 309. Best Time to Buy and Sell Stock with Cooldown
- 【jQuery】图片灯箱插件——lightBox
- 普法知识(43):法定职责必须为、法无授权不可为
- Android内核之FrameWork学习
- 【jQuery】表单插件——ajaxForm()方法
- spark-1.2.0 集群环境搭建
- "Google Chrome 未响应。 是否立即重新启动?"的解决方法
- 【jQuery】表单验证插件——validate
- UI交互设计的网站
- 动态修改UINavigationBar的背景色
- Codeforces Educational Codeforces Round 3 E. Minimum spanning tree for each edge LCA链上最大值
- Codeforces Educational Codeforces Round 3 D. Gadgets for dollars and pounds 二分,贪心
- Codeforces Educational Codeforces Round 3 C. Load Balancing 贪心
- (JavaFX 版)综合性实验 学生成绩分析程序
- Codeforces Educational Codeforces Round 3 B. The Best Gift 水题
- Codeforces Educational Codeforces Round 3 A. USB Flash Drives 水题