python_leetcode326. 3的幂

给定一个整数,写一个函数来判断它是否是 3 的幂次方。

示例 1:

输入: 27
输出: true

示例 2:

输入: 0
输出: false

示例 3:

输入: 9
输出: true

示例 4:

输入: 45
输出: false

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """

进阶:
你能不使用循环或者递归来完成本题吗?

方法一:循环

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

方法二:因为n为int类型,其最大为3的19次方。故:

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n > 0 and 3**19 % n == 0

方法三:取n以3为底的对数k,判断3的k次方是否为n

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n>0 and 3**round(math.log(n,3))==n

猜你喜欢

转载自blog.csdn.net/AntiZheng/article/details/82885061