卖萌的弱渣

I am stupid, I am hungry.

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?

Solution

  • Java:Find the maximum integer(1162261467) that is a power of 3 and check if it is a multiple of the given input.
(Power-of-Three.java) download
1
2
3
4
5
public class Solution {
    public boolean isPowerOfThree(int n) {
        return (n>0 && 1162261467 %n ==0);
    }
}
  • Python: 求对数,然后乘方,判断得数是否相等
(Power-of-Three.py) download
1
2
3
4
5
6
7
8
class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n > 0 and 3 ** (round(math.log(n,3))) == n