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?
没啥意思的题,循环解法。
class Solution {
public:
bool isPowerOfThree(int n) {
while (n >= 3) {
if (n % 3 != 0) {
return false;
}
n /= 3;
}
return (n == 1);
}
};
纯数学的东西。
class Solution {
public:
bool isPowerOfThree(int n) {
static double const epsilon = 1e-15;
double power = log10(n) / log10(3);
return (power - floor(power) < epsilon);
}
};