[LeetCode] Power of Three | Power of Two

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

Follow up:
Could you do it without using any loop / recursion?

解题思路

log运算。

实现代码

//Runtime: 18 ms
public class Solution {
    public boolean isPowerOfThree(int n) {
        double res = Math.log(n) / Math.log(3);
        return Math.abs(res - Math.round(res)) < 1e-10;
    }
}

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

解题思路

2的n次方,必然大于0;而且二进制位中只有一个1。

实现代码

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

你可能感兴趣的:(LeetCode)