leetcode 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?
题目地址: leetcode Power of Three
题目大意:
给定一个整数,判断是否是3的整数幂
思路
方法一
循环判断,每次除以3
C++ 1
2
3
4
5
6
7
8
9
10
11class Solution {
public:
bool isPowerOfThree(int n) {
if(n <= 0) return false;
while(n > 1){
if(n %3 != 0) return false;
n/=3;
}
return true;
}
};
Python 1
2
3
4
5
6
7
8
9
10
11class 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
方法二
递归
C++ 1
2
3
4
5
6
7
8class Solution {
public:
bool isPowerOfThree(int n) {
if (n <= 0) return false;
if (n == 1) return true;
return n % 3 == 0 && isPowerOfThree(n / 3);
}
};
Python 1
2
3
4
5
6
7
8
9class 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)
方法三
取对数
C++ 1
2
3
4
5
6class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && pow(3, round(log(n) / log(3))) == n;
}
};
Java 1
2
3
4
5class Solution {
public boolean isPowerOfThree(int n) {
return n > 0 && Math.pow(3, Math.round(Math.log(n) / Math.log(3))) == n;
}
}
Python 1
2
3
4
5
6
7class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and 3 ** round(math.log(n, 3)) == n
本文是leetcode 326 Power of Three 题解,更多本博客题解见 https://www.hrwhisper.me/leetcode-algorithm-solution/