leetcode

    xiaoxiao2021-03-25  171

    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); }
    转载请注明原文地址: https://ju.6miu.com/read-6073.html

    最新回复(0)