LeetCode 326 Power of Three (Python)

Posted by 小明MaxMing on April 27, 2021

题目

Given an integer n, return true if it is a power of three. Otherwise, return false.

An integer n is a power of three, if there exists an integer x such that n == 3x.

解题思路

  1. 模3,判断是否为0,如果不是0则必须为1
  2. 输入最大3^19,判断是否为3^30约数
  3. 取log,判断是否为整数

代码

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n == 0:
            return False
        while n % 3 == 0:
            n /= 3
        return n == 1
class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        return n > 0 and 3**20 % n == 0
class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n <= 0:
            return False
        t = math.log(n, 3)
        return math.fabs(t - round(t)) < 0.0000000001

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅