1. 程式人生 > 其它 >leetcode——2的冪

leetcode——2的冪

技術標籤:C++面試

連結:https://leetcode-cn.com/problems/power-of-two/

題目:給定一個整數,編寫一個函式來判斷它是否是 2 的冪次方。

示例:

1、
輸入: 1
輸出: true
解釋: 20 = 1

2、
輸入: 16
輸出: true
解釋: 24 = 16

3、
輸入: 218
輸出: false

思考:

2^0 = 1 = 00000001

2^1 = 2 = 00000010
2^2 = 4 = 00000100

2^7 = 128 = 10000000

2的冪特徵:最高位是1,其餘位為0。 如果輸入值小於等於0, 則必返回false

方案一:

x \land -x = x

時間複雜度O(log^n)

空間複雜度O(1)

方案二:位運算,獲取二進位制最右邊的1

-x = \lnot {x} + 1 說明:x的補碼為x按位取反加1

{x} \land {-x}保留x最右邊的1

如果x \land -x = x則x是2的n次冪

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n <= 0) return false;
        return (n & (-n)) == n;
    }
};

時間複雜度O(1)

空間複雜度O(1)

方案三:位運算,去除二進位制最右邊的1

x - 1會把x最右邊的1設定為0, 最右邊1的較低位設定為1

x \land (x-1)會把x最右邊1及較低位都設定為1,即將最右邊1設定為0

x \land (x-1) == 0如果x \land (x-1) == 0, 則x為2的n次冪

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n <= 0) return false;
        return (n & (n - 1)) == 0;
    }
};

時間複雜度O(1)

空間複雜度O(1)