[LeetCode] 326. Power of Three 3的次方数

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?

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

给一个整数,写一个函数来判断此数是不是3的次方数。

类似的题目Power of Two 中,由于2的次方数的特点,用位操作很容易。而3的次方数没有显著的特点,最直接的方法就是不停地除以3,最后判断是否能整除。

follow up是否不用任何循环或递归。

解法1: 循环

解法2: 迭代

解法3:取对数

Java:

class Solution {
    public boolean isPowerOfThree(int n) {
        return n > 0 && Math.pow(3, Math.round(Math.log(n) / Math.log(3))) == n;
    }
}  

Python:

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0: return False
        while n != 1:
            if n % 3 != 0: return False
            n /= 3
        return True 

Python:

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0: return False
        if n == 1: return True
        return n % 3 == 0 and self.isPowerOfThree(n / 3) 

Python:

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

Python:

class Solution(object):
    def isPowerOfThree(self, n):
        return n > 0 and (math.log10(n)/math.log10(3)).is_integer()

Python:  

class Solution(object):
    def __init__(self):
        self.__max_log3 = int(math.log(0x7fffffff) / math.log(3))
        self.__max_pow3 = 3 ** self.__max_log3

    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n > 0 and self.__max_pow3 % n == 0

C++:

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n <= 0) return false;
        while(n > 1){
            if(n %3 != 0) return false;
             n/=3;
        }
        return true;
    }
};  

C++:

class Solution {
public:
	bool isPowerOfThree(int n) {
		if (n <= 0) return false;
		if (n == 1) return true;
		return n % 3 == 0 && isPowerOfThree(n / 3);
	}
};  

C++:

class Solution {
public:
	bool isPowerOfThree(int n) {
		return n > 0 && pow(3, round(log(n) / log(3))) == n;
	}
};

  

  

 

All LeetCode Questions List 题目汇总

posted @ 2018-05-17 05:22  轻风舞动  阅读(431)  评论(0编辑  收藏  举报