ITeye博客

Power of Three

KickCode · 2016-02-28 04:58 · Leetcode · 编程语言 · Markdown

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?

判断一个整数是否为3的幂。如果一个整数是3的幂,那么就可以表示为 3 ^ x = n => log(3^x) = log(n) => xlog(3) = log(n) => x = log(n) / log(3)。我们只需要判断x是否为整数就可以了,代码如下:


public class Solution {
    public boolean isPowerOfThree(int n) {
        if(n <= 0) return false;
        double d = Math.log10(n) / Math.log10(3);
        return d % 1 == 0 ? true : false;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。