[LeetCode] Power of Two 判斷2的次方數


 

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

Example 1:

Input: 1
Output: true

Example 2:

Input: 16
Output: true

Example 3:

Input: 218
Output: false

 

這道題讓我們判斷一個數是否為2的次方數,而且要求時間和空間復雜度都為常數,那么對於這種玩數字的題,我們應該首先考慮位操作 Bit Operation。在LeetCode中,位操作的題有很多,比如比如 Repeated DNA SequencesSingle Number,  Single Number II Grey Code Reverse BitsBitwise AND of Numbers RangeNumber of 1 Bits 和 Divide Two Integers 等等。那么我們來觀察下2的次方數的二進制寫法的特點:

1     2       4         8         16   ....

1    10    100    1000    10000 ....

那么我們很容易看出來2的次方數都只有一個1,剩下的都是0,所以我們的解題思路就有了,我們只要每次判斷最低位是否為1,然后向右移位,最后統計1的個數即可判斷是否是2的次方數,代碼如下:

 

解法一:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        int cnt = 0;
        while (n > 0) {
            cnt += (n & 1);
            n >>= 1;
        }
        return cnt == 1;
    } 
};

 

這道題還有一個技巧,如果一個數是2的次方數的話,根據上面分析,那么它的二進數必然是最高位為1,其它都為0,那么如果此時我們減1的話,則最高位會降一位,其余為0的位現在都為變為1,那么我們把兩數相與,就會得到0,用這個性質也能來解題,而且只需一行代碼就可以搞定,如下所示:

 

解法二:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return (n > 0) && (!(n & (n - 1)));
    } 
};

 

類似題目:

Number of 1 Bits

Power of Four

Power of Three

 

參考資料:

https://leetcode.com/problems/power-of-two/discuss/63974/Using-nand(n-1)-trick

https://leetcode.com/problems/power-of-two/discuss/63972/One-line-java-solution-using-bitCount

 

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


免責聲明!

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



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