leetcode 231. Power of Two
2016-03-31 15:12
344 查看
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.
我的做法很丑陋,先贴上我的代码,再附上别人的代码。这就是美女与野兽。
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
我的做法很丑陋,先贴上我的代码,再附上别人的代码。这就是美女与野兽。
public class Solution { public boolean isPowerOfTwo(int n) { if(n<=0){return false;} if(n==1){ return true; } if(n%2 !=0){ return false; } while(n%2 ==0){ if(n==2){ return true; } else{ n=n/2; } } return false; } }我的代码冗长不简洁,下面在网上看到的别人的方法,很不错。巧妙运用了2的次幂对应的二进制数,只有一个1.
public class Solution { public boolean isPowerOfTwo(int n) { return n > 0 && ((n & (n - 1)) == 0 ); } }
相关文章推荐
- MyBatis crud操作
- Python之异步IO&RabbitMQ&Redis
- 网易实习生真题(二叉树)
- 管道和FIFO
- js实现定时添加代码
- 数据库索引
- Android中解决scrollview中嵌套listview的listview只显示一行的问题
- bzoj3011 可并堆
- ${pageContext.request.contextPath} JSP路径问题
- leetcode04-Median of Two Sorted Arrays-python
- unity3d的playmaker插件使用教程,四、物品破坏,道具拾取
- Tomcat内存溢出的几点方案
- altium designer 软件常用技巧总结(实时更新)
- NATS服务器配置详解
- 文章标题
- 升级数据库的最佳写法
- keepalived与lvs 调度算法
- linux系统下mysql跳过密码验证登录
- 我的2016年linux学习决心书
- 项目2——游戏中的角色2