您的位置:首页 > 其它

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.

我的做法很丑陋,先贴上我的代码,再附上别人的代码。这就是美女与野兽。

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 );
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: