326. Power of Three
参考相似题 [LeetCode] 231. Power of Two
Given an integer, write a function to determine if it is a power of three.
给一个整数,写一个函数判断其是否是3的幂
Follow up:
Could you do it without using any loop / recursion?(不用循环和递归)
思路:
- 刚开始想的就是判断边界值,发现3^19 = 1162261467,
- 3^20 > 2147483647(int 最大值)
- 3^0 = 1 (3的最小幂)
- 在1~1162261467范围内所有的3的幂均能被1162261467整除
代码如下:
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfThree(int n) {
if(n<=0 || n>2147483647)//3的幂最小是1 int最大为2147483647
return false;
// 1162261467 is 3^19, 3^20 is bigger than int
return 1162261467%n==0;
}
};
int main()
{
Solution s;
int a =0;
cin >> a;
cout << s.isPowerOfThree(a) << endl;
return 0;
}