[leedcode 231] Power of Two

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;
    }
}
原文地址:https://www.cnblogs.com/qiaomu/p/4713415.html