题目描述:
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上的题解有对几种解法进行一个分析,值得去看一看。