leetcode_326. Power of Three-判断是否3的次方

来源:互联网 发布:一天一包烟 烟瘾 知乎 编辑:程序博客网 时间:2024/05/16 09:06

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的次方?

法1:网友神奇方法

public boolean isPowerOfThree(int n) {    // 1162261467 is 3^19,  3^20 is bigger than int      return ( n>0 &&  1162261467%n==0);}

法2:借助对数函数

    // 借助对数函数,注意,对数函数在求log(243,3)时得到4.999999999999999而非5,所以要注意    public boolean isPowerOfThree(int n) {        if(n<=0) return false;        double d = log(n, 3);        int t = (int) Math.floor(d+0.1);        return n==Math.pow(3, t);    }    public double log(double value, double base) {        return Math.log(value) / Math.log(base);    }
0 0