1. 程式人生 > 其它 >【數學】力扣326:3 的冪

【數學】力扣326:3 的冪

給定一個整數,寫一個函式來判斷它是否是 3 的冪次方。如果是,返回 true ;否則,返回 false 。
整數 n 是 3 的冪次方需滿足:存在整數 x 使得 $ n = 3^{x}$ 。
示例:

輸入:n = 27
輸出:true

用到的函式:

  1. math.log()
import math
math.log(x[, base])

預設base為自然對數e
2. round(x [, n]) 返回浮點數x的四捨五入值

方法1:暴力解法

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        while n > 1 and n % 3 == 0:
            n //= 3
        return n == 1

時間複雜度:O(logn)。當 n 是 3 的冪時,需要除以 3 的次數為 $ log_{3}n = O(logn) $;當 n 不是 3 的冪時,需要除以 3 的次數小於該值。
空間複雜度:O(1)。

方法2:取巧
思路1:利用對數。設 $ log_{3}n = x $,如果 n 是 3 的整數次方,那麼 x 一定是大於 0 的整數。

import math
class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        return n > 0 and math.log(n, 3) % 1 == 0

因為math.log()精度問題,n == 243 時通過不了。。。
可以使用round

函式解決:

import math
class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        return n > 0 and n == 3 ** round(math.log(n, 3))

思路2:因為在 int 範圍內 3 的最大次方是 $ 3 ^ {19} = 1162261467 $,如果 n 是 3 的整數次方,那麼 1162261467 除以 n 的餘數一定是零;反之亦然。

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        return n > 0 and 1162261467 % n == 0

時間複雜度:O(1)。
空間複雜度:O(1)。