导航

(easy)LeetCode 231.Power of Two

Posted on 2015-07-31 14:57  骄阳照林  阅读(117)  评论(0编辑  收藏  举报

Given an integer, write a function to determine if it is a power of two.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

代码如下:

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if(n<=0) return false;
        if(n==1) return true;
        int mod=n;
        while(mod>=2 && mod%2==0){
            mod/=2;
        }
        if(mod>=2 && mod%2!=0)
           return false;
         else
           return true;
    }
}

  运行结果: