231. Power of Two
来源:互联网 发布:微淘号达人淘宝达人 编辑:程序博客网 时间:2024/06/04 18:15
1.题目
Given an integer, write a function to determine if it is a power of two.
2.分析
这道题在easy难度中比较简单了,之所以拿出来说,是因为之前有问到过,当时问我有没有其他解法,就是没有想到位操作- -,其实很多判断数属性的题都可以通过位操作解题。
3.解题
(1)我的解题:
public class Solution {
public boolean isPowerOfTwo(int n) {
// 边界处理
if(n<=0){
return false;
}
if(n==1){
return true;
}
int a = n/2;
int b = n%2;
if(b==1){
return false;
}
while(a!=1){
b += a%2;
a = a/2;
}
if(b!=0){
return false;
}
return true;
}
}
看到一个比较简洁的解题:
publicbooleanisPowerOfTwo(int n){return ((n & (n-1))==0 && n>0);}//利用的位操作的性质
4.总结
很多这种判别进制的问题,其实都可以通过位操作来进行,我采用的是比较笨的方法,递归- -,时间效率很差,虽然对于这种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
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- 231. Power of Two
- SSH整合
- 126397
- idea2017激活、注册码
- 使用空间工具(Spatial Tools)导入ESRI格式地图数据
- CentOS 7 yum方式快速安装MongoDB
- 231. Power of Two
- Spring MVC 拦截静态资源的解决方案
- 抽象工厂模式
- Mysql安装
- Eclipse开发JSP页面,xhtml页面卡死的解决方法
- 【2017.07.27】不要让未来的你,讨厌现在的自己
- 安装 GNU 的 C/C++ 编译器
- HDU-4609-FFT
- LeetCode之字符串(C++)的切割简单实现