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?
Method:
Power of Three does not follow the similar rule of power of four. We can use log operation to solve this problem. However, attention should be paid to accuracy of numbers.
C++:
class Solution {
public:
bool isPowerOfThree(int n) {
double ans = log10(n)/log10(3);
return ans-int(ans)==0;
}
};
网友评论