LeetCode-326. Power of Three

Description:

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

判断一个整数是否是3的幂。

基于公式log3^n可以得出y=lg(n)/log(3)如果y正好是个整数的话,说明n是3的幂。也可以使用循环除3的方法,也不是很浪费时间循环不了多少次。

public class Solution {
    public boolean isPowerOfThree(int n) {
        
        double ans = Math.log(n) / Math.log(3);
        return Math.abs(ans - Math.round(ans)) < 0.000000000001;
    }
}

posted @ 2016-02-18 18:51  Pickle  阅读(287)  评论(0编辑  收藏  举报