Leetcode解题: Power of Three (326)

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?

解法1:Loop

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool isPowerOfThree(int n) {
if (n < 1) return false;
while ( n >= 3) {
if (n % 3 != 0) {
return false;
}
n = n / 3;
}
if (n == 1) {
return true;
}
return false;
}
};

Java

1

解法2:Follow up

如果一个数是3^x,那么以3为底数做log,结果一定是整数。运用log3(x) = log10(x) / log10(3)
C++

1
2
3
4
5
6
7
class Solution {
public:
bool isPowerOfThree(int n) {
double res = log10(n) / log10(3);
return (res - (int)res) == 0;
}
};