0%

326. 3的幂

326. 3的幂

递归
1
2
3
4
5
6
7
8
class Solution {
public:
bool isPowerOfThree(int n) {
if(n < 3)
return n == 1;
return n % 3 == 0 ? isPowerOfThree(n / 3) : false;
}
};
循环
1
2
3
4
5
6
7
8
class Solution {
public:
bool isPowerOfThree(int n) {
while(n && n % 3 == 0)
n /= 3;
return n == 1;
}
};
数学
1
2
3
4
5
6
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
};

在int范围内,3的幂的最大数是1162261467,且1162261467的所有约数都是3的幂,且包含所有情况,所以只需要判断n是不是1162261467的约束就可以