leetcode 326. Power of Three

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章