326_Power_of_Three

326. Power of Three

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

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

简介

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

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

解决方案如下:

n = 3**log3n 

代码如下

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

总结

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



你可能感兴趣的:(LeetCode,power,幂指数)