[LeetCode] Power of Four 判斷4的次方數


 

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example 1:

Input: 16
Output: true 

Example 2:

Input: 5
Output: false

Follow up: Could you solve it without loops/recursion?

Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.

 

這道題讓我們判斷一個數是否為4的次方數,那么最直接的方法就是不停的除以4,看最終結果是否為1,參見代碼如下:

 

解法一:

class Solution {
public:
    bool isPowerOfFour(int num) {
        while (num && (num % 4 == 0)) {
            num /= 4;
        }
        return num == 1;
    }
};

 

還有一種方法是跟 Power of Three 中的解法三一樣,使用換底公式來做,講解請參見之前那篇博客:

 

解法二:

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && int(log10(num) / log10(4)) - log10(num) / log10(4) == 0;
    }
};

 

下面這種方法是網上比較流行的一種解法,思路很巧妙,首先根據 Power of Two 中的解法二,我們知道 num & (num - 1) 可以用來判斷一個數是否為2的次方數,更進一步說,就是二進制表示下,只有最高位是1,那么由於是2的次方數,不一定是4的次方數,比如8,所以我們還要其他的限定條件,我們仔細觀察可以發現,4的次方數的最高位的1都是計數位,那么我們只需與上一個數 (0x55555555) <==> 1010101010101010101010101010101,如果得到的數還是其本身,則可以肯定其為4的次方數:

 

解法三:

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && !(num & (num - 1)) && (num & 0x55555555) == num;
    }
};


或者我們在確定其是2的次方數了之后,發現只要是4的次方數,減1之后可以被3整除,所以可以寫出代碼如下:

 

解法四:

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && !(num & (num - 1)) && (num - 1) % 3 == 0;
    }
};

 

類似題目:

Power of Three

Power of Two

 

參考資料:

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

https://leetcode.com/problems/power-of-four/discuss/80457/Java-1-line-(cheating-for-the-purpose-of-not-using-loops)

https://leetcode.com/problems/power-of-four/discuss/80460/1-line-C%2B%2B-solution-without-confusing-bit-manipulations

 

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


免責聲明!

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



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