326_Power_of_Three

326. Power of Threeshell

Given an integer, write a function to determine if it is a power of three.oop

Follow up:
Could you do it without using any loop / recursion?spa

简介code

这个题目很简单,使用一个简单的循环就能够完成,可是题目中有说明:你能够不使用循环和递归的状况下完成它吗?我想说:那果断啊,否则尼?orm

然而我想了很久却没有思路,真心以为循环的路被堵住之后,已经无路可走了,实在没有想法,偷偷瞄了一眼别人的code,最后才完成最后的提交。递归

解决方案以下:three

n = 3**log3n it

代码以下io

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

总结function

看上去越简单的题目,每每越难解决,

本站公众号
   欢迎关注本站公众号,获取更多信息