LeetCode 231. Power of Two

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.

【题目分析】
判断一个数是否是2的某次方
 
【思路】
1. 利用Java自带函数 
public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n == 0 ? false : n == Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
    }
}

Math.pow() 进行指数运算;

Math.log() 进行底数为e的对数运算;

Math.round() 进行四舍五入运算;

n == Math.pow(2, Math.round(Math.log(n) / Math.log(2))) 这一句很巧妙地判断了n是否是2的某次方数。

2. 位运算

2的次方可以用1向左移位得到

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n < 1) return false;
        
        int m = 1;
        for (int i = 1; i < 32 && m <= n; i++) {
            if(m == n) return true;
            m <<= 1;
        }
        
        return false;
    }
}

 

3. Power of 2 means only one bit of n is '1', so use the trick n&(n-1)==0 to judge whether that is the case

2的某次方只有一位1,该数减一与该数位与的话结果为0的话肯定是2的某次方。

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n < 1) return false;
        return (n & (n-1)) == 0;
    }
}

 

 

posted @ 2016-04-07 17:15  Black_Knight  阅读(195)  评论(0编辑  收藏  举报