136-326. 3的幂数

给定一个整数,写一个函数来判断它是否是 3 的幂次方。如果是,返回 true ;否则,返回 false 。(第一个我写的)

class Solution(object):
    def isPowerOfThree1(self, n):
        """我的偷懒解法
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        return str(math.log(n, 3)).endswith(".0")

    def isPowerOfThree2(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False

        while n % 3 == 0:
            n //= 3
        return n == 1

    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        import math
        if n <= 0:
            return False
        res = math.log10(n)/math.log10(3)
        return res == int(res)


if __name__ == '__main__':
    import math
    s = Solution()
    n = 45
    print(s.isPowerOfThree(n))
原文地址:https://www.cnblogs.com/liuzhanghao/p/14261192.html