【Leetcode Algorithm】Power of Two

来源:互联网 发布:软件体系架构 pdf 编辑:程序博客网 时间:2024/06/05 16:20
Given an integer, write a function to determine if it is a power of two.
第一次尝试代码:
public class Solution {    public boolean isPowerOfTwo(int n) {        //如果为0,则false        if(n==0){            return false;        }        //2^0=1        if(n==1){            return true;        }        //n为奇数则肯定不是,若是偶数则递归解决        if(n%2!=0){            return false;        }        else{            Solution s = new Solution();            return s.isPowerOfTwo(n/2);        }    }}


第二次尝试代码:
public class Solution {    public boolean isPowerOfTwo(int n) {        //负数与0都不是        if(n<=0){            return false;        }        //如果n与n-1与运算之后不为0,则表明n的二进制数1的个数大于1,则判定肯定不是        else if((n&(n-1))!=0){            return false;        }        else{            return true;        }    }}


0 0
原创粉丝点击