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上的題解有對幾種解法進行一個分析,值得去看一看。

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