leetcode 231. Power of Two
来源:互联网 发布:数的读法 c语言 编辑:程序博客网 时间:2024/05/20 00:37
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.
我的做法很丑陋,先贴上我的代码,再附上别人的代码。这就是美女与野兽。
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 ); } }
0 0
- [leetcode] 231.Power of Two
- LeetCode ||231. Power of Two
- [LeetCode]231.Power of Two
- Leetcode 231. Power of Two
- leetcode 231. Power of Two
- 231. Power of Two LeetCode
- [LeetCode]231. Power of Two
- [LeetCode]231. Power of Two
- LeetCode 231. Power of Two
- [leetcode] 231. Power of Two
- leetcode 231. Power of Two
- LeetCode *** 231. Power of Two
- leetcode 231. Power of Two
- LeetCode 231. Power of Two
- Leetcode-231. Power of Two
- #leetcode#231. Power of Two
- 231.[Leetcode]Power of Two
- Leetcode 231. Power of Two
- 数据库设计原则
- 版本问题和获取秘钥签名
- 结构体
- js中的正则表达式
- velocity的HelloWord
- leetcode 231. Power of Two
- Android 友盟第三方消息推送使用
- 截获webView点击事件
- qt环境下使用OpenGL
- 拨钟问题
- 平年,闰年,回文数
- LValue RValue
- 超好用的前嗅ForeSpider爬虫软件教程
- 各种音视频编解码学习详解 h264 ,mpeg4 ,aac 等所有音视频格式