1. 程式人生 > >Python實現"3的冪"的兩種方法

Python實現"3的冪"的兩種方法

給定一個整數,寫一個函式判斷它是否是3的冪

Example 1:

Input: 27
Output: true

Example 2:

Input: 0
Output: false

Example 3:

Input: 9
Output: true

Example 4:

Input: 45
Output: false

進階:

你能不適用迴圈或者迭代完成這個題麼?

1:累除3

迴圈

def isPowerOfThree(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
        """
        if n == 0:
            return False
        if n == 1:
            return True
        if n % 3 == 0:
            return self.isPowerOfThree(n // 3)
        else:
            return False

2:round()+math.log()方法(參考他人)

def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        return 3 ** round(math.log(n, 3)) == n

類似方法(參考他人)

def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        sum = 3 ** 100
        return sum % n == 0