Power of Three——Math

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?

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        #method 1
        return n > 0 and 3 ** round(math.log(n,3)) == n
        
        #method 2
        if n < 0:
        	return False
        if n == 0:
        	return False
        re = math.log(n) / math.log(3.0)
        i = round(re,0)
        if abs(re-i) < 1e-10:
        	return True
        else:
        	return False

猜你喜欢

转载自qu66q.iteye.com/blog/2317225