首页 > 其他 > 详细

[leedcode 231] Power of Two

时间:2015-08-08 17:56:54      阅读:230      评论:0      收藏:0      [点我收藏+]

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

 

[leedcode 231] Power of Two

原文:http://www.cnblogs.com/qiaomu/p/4713415.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!