友情支持

如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜

支付宝

微信

有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。

wx jikerizhi

公众号的微信号是: jikerizhi因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。

326. Power of Three

发现一个很奇怪的问题:如果通过计算相乘来判断,则会超时;如果通过相除来判断,则能顺利通过。感觉计算量是一样的啊?为什会有这么大的差距啊?

利用对数计算也不失为一个很好的办法!

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

Example 1:

Input: 27
Output: true

Example 2:

Input: 0
Output: false

Example 3:

Input: 9
Output: true

Example 4:

Input: 45
Output: false

Follow up:

Could you do it without using any loop / recursion?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
 * Runtime: 11 ms, faster than 89.24% of Java online submissions for Power of Three.
 *
 * Memory Usage: 36.4 MB, less than 6.25% of Java online submissions for Power of Three.
 *
 * Copy from: https://leetcode.com/problems/power-of-three/solution/[Power of Three solution - LeetCode]
 */
public boolean isPowerOfThree(int n) {
    return (Math.log10(n) / Math.log10(3)) % 1 == 0;
}
/**
 * Runtime: 11 ms, faster than 89.24% of Java online submissions for Power of Three.
 *
 * Memory Usage: 36.6 MB, less than 6.25% of Java online submissions for Power of Three.
 *
 * Copy from: https://leetcode.com/problems/power-of-three/solution/[Power of Three solution - LeetCode]
 */
public boolean isPowerOfThreeDiv(int n) {
    if (n < 1) {
        return false;
    }
    while (n % 3 == 0) {
        n /= 3;
    }
    return n == 1;
}

/**
 * Time Limit Exceeded
 */
public boolean isPowerOfThreeMult(int n) {
    if (n < 1) {
        return false;
    }
    int temp = 1;
    for (int i = 0; temp <= n && i < n; i++) {
        if (temp == n) {
            return true;
        }
        temp *= 3;
    }
    return false;
}