leetcode 326. Power of Three(不用循环或递归)

leetcode 326. Power of Three(不用循环或递归)

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的幂,最简单的也最容易想到的办法就是递归判断,或者循环除。

有另一种方法就是,求log以3为底n的对数。类似 如果n=9,则结果为2,如果是10,则结果肯定不是个整数。所以第一次提交如下:

public class Solution {
   
    public boolean isPowerOfThree(int n) {
        if(0 == n)
            return false;
        double res = Math.log(n)/Math.log(3);
        return Math.floor(res) == Math.ceil(res);
       
    }
}

但是并没有ac,原因是243的时候出错,后来分析发现是因为java 浮点数的原因。参考别人的修改了下,如下:

public class Solution {
    private static final double epsilon = 10e-15;

    public boolean isPowerOfThree(int n) {
        if(0 == n)
            return false;
        double res = Math.log(n)/Math.log(3);
        //return Math.floor(res) == Math.ceil(res);
        return Math.abs(res - Math.round(res)) < epsilon;
    }
}

ac

原文地址:https://www.cnblogs.com/tina-smile/p/5115810.html