您的位置:首页 > 其它

[leedcode 231] Power of Two

2015-08-08 16:38 155 查看
Given an integer, write a function to determine if it is a power of two.

public class Solution {
//注意0和负数都返回false!!!

/*public boolean isPowerOfTwo(int n) {
if(n<=0) return false;//此方法关键是使用Integer.toBinaryString(n),将整数转化为二进制的字符串
String m=Integer.toBinaryString(n);
for(int i=1;i<m.length();i++){
if(m.charAt(i)=='1') return false;
}
return true;
}*/

/* public boolean isPowerOfTwo(int n) {
if(n<=0) return false;
while(n>0){
if(n!=1&&n%2==1) return false;
n=n>>1;
}
return true;
}*/
public boolean isPowerOfTwo(int n) {
if(n<=0) return false;
return (n&(n-1))==0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: