[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?Credits: Special thanks to @dietpepsi for addin

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?

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

前提学习:
Java Math的floor,round,ceil函数小结

想法:

3^x=n

log(3^x) = log(n)

x log(3) = log(n)

x = log(n) / log(3)

We need to

largest number power of 3, is 1162261467, we can use this to calculate the float precision. 0.0000000001 at least

Math.log(1162261468)/log(3)

private static final double epsilon = 10e-15;

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

常规办法(AC过的):

public boolean isPowerOfThree(int n) {
        if (n == 0)
            return false;
        if (n == 1)
            return true;
        if (n % 3 == 0)
            return isPowerOfThree(n / 3);
        return false;
    }
目录
相关文章
LeetCode 342. Power of Four
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
76 0
LeetCode 342. Power of Four
|
人工智能 索引
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
|
Java C++
LeetCode之Power of Two
LeetCode之Power of Two
115 0
LeetCode 326 Power of Three(3的幂)(递归、Log函数)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50540517 翻译 给定一个整型数,写一个函数决定它是否是3的幂(翻译可能不太合适…… 跟进: 你是否可以不用任何循环或递归来完成。
782 0
LeetCode 231 Power of Two(2的幂)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50541137 翻译 给定一个整型数,写一个函数来决定它是否是2的幂。
700 0