[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;
    }
}

 

posted @ 2015-08-08 16:38  ~每天进步一点点~  阅读(180)  评论(0编辑  收藏  举报