[LeetCode] Power of Three 判斷3的次方數


 

Given an integer, write a function to determine if it is a power of three.

Example 1:

Input: 27
Output: true

Example 2:

Input: 0
Output: false

Example 3:

Input: 9
Output: true

Example 4:

Input: 45
Output: false

Follow up:
Could you do it without using any loop / recursion?

 

這道題讓我們判斷一個數是不是3的次方數,在LeetCode中,有一道類似的題目Power of Two,那道題有個非常簡單的方法,由於2的次方數實在太有特點,最高位為1,其他位均為0,所以特別容易,而3的次方數沒有顯著的特點,最直接的方法就是不停地除以3,看最后的迭代商是否為1,要注意考慮輸入是負數和0的情況,參見代碼如下:

 

解法一:

class Solution {
public:
    bool isPowerOfThree(int n) {
        while (n && n % 3 == 0) {
            n /= 3;
        }
        return n == 1;
    }
};

 

題目中的Follow up讓我們不用循環,那么有一個投機取巧的方法,由於輸入是int,正數范圍是0-231,在此范圍中允許的最大的3的次方數為319=1162261467,那么我們只要看這個數能否被n整除即可,參見代碼如下:

 

解法二:

class Solution {
public:
    bool isPowerOfThree(int n) {
        return (n > 0 && 1162261467 % n == 0);
    }
};

 

最后還有一種巧妙的方法,利用對數的換底公式來做,高中學過的換底公式為logab = logcb / logca,那么如果n是3的倍數,則log3n一定是整數,我們利用換底公式可以寫為log3n = log10n / log103,注意這里一定要用10為底數,不能用自然數或者2為底數,否則當n=243時會出錯,原因請看這個帖子。現在問題就變成了判斷log10n / log103是否為整數,在c++中判斷數字a是否為整數,我們可以用 a - int(a) == 0 來判斷,參見代碼如下:

 

解法三:

class Solution {
public:
    bool isPowerOfThree(int n) {
        return (n > 0 && int(log10(n) / log10(3)) - log10(n) / log10(3) == 0);
    }
};

 

類似題目:

Power of Two

Power of Four

 

參考資料:

https://leetcode.com/problems/power-of-three

https://leetcode.com/problems/power-of-three/discuss/77856/1-line-java-solution-without-loop-recursion

https://leetcode.com/problems/power-of-three/discuss/77876/**-A-summary-of-all-solutions-(new-method-included-at-15%3A30pm-Jan-8th)

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM