題目描述:
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?
解題思路:
從極大3的指數值入手,從編程語言存儲的數字有個上下限這個特點入手就很容易了。
class Solution {
public:
bool isPowerOfThree(int n) {
if(n <= 0)
return 0;
return (pow3Max % n == 0);
}
private:
const int log3IntMax = log(INT_MAX) / log(3);
const int pow3Max = pow(3, log3IntMax);
};
leetcode上的題解有對幾種解法進行一個分析,值得去看一看。