1. Description
2. Solution
- Version 1
class Solution {
public:
bool isPowerOfThree(int n) {
if(n <= 0) {
return false;
}
while(n != 1) {
if(n % 3) {
return false;
}
n /= 3;
}
return true;
}
};
- Version 2
class Solution {
public:
bool isPowerOfThree(int n) {
// 1162261467 is 3^19, 3^20 is bigger than int
return ((n > 0) && (1162261467 % n == 0));
}
};
- Version 3
class Solution {
public:
bool isPowerOfThree(int n) {
return fmod(log10(n) / log10(3), 1) == 0;
}
};