1: class Solution {
2: public:
3: bool isPowerOfThree(int n) {
4: return n > 0 && (n == 1 || (n % 3 == 0 && isPowerOfThree(n / 3)));
5: }
6: };
Anyway, there is a mathematical version.
1: class Solution {
2: public:
3: bool isPowerOfThree(int n) {
4: int maxThrees = (int) pow(3, (int)(log(0x7FFFFFFF)/log(3)));
5: return n > 0 && maxThrees % n == 0;
6: }
7: };
No comments:
Post a Comment