Skip to content

326 power of three

326. Power of Three

题目: https://leetcode.com/problems/power-of-three/

难度 : Easy

直接就上的递归

class Solution(object):
    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)
        return False

有一个follow up,可否不用 loop/recursion

看到了取巧的办法,因为是Given an integer,是有范围的(<2147483648),存在能输入的最大的3的幂次,即 3^19=1162261467。

只用检查是否能被这个数整除

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



回到顶部