leetcode——2的冪
阿新 • • 發佈:2021-01-28
連結:https://leetcode-cn.com/problems/power-of-two/
題目:給定一個整數,編寫一個函式來判斷它是否是 2 的冪次方。
示例:
1、
輸入: 1
輸出: true
解釋: 20 = 1
2、
輸入: 16
輸出: true
解釋: 24 = 16
3、
輸入: 218
輸出: false
思考:
2的冪特徵:最高位是1,其餘位為0。 如果輸入值小於等於0, 則必返回false
方案一:
時間複雜度
空間複雜度
方案二:位運算,獲取二進位制最右邊的1
說明:x的補碼為x按位取反加1
保留x最右邊的1
如果則x是2的n次冪
class Solution { public: bool isPowerOfTwo(int n) { if (n <= 0) return false; return (n & (-n)) == n; } };
時間複雜度
空間複雜度
方案三:位運算,去除二進位制最右邊的1
會把x最右邊的1設定為0, 最右邊1的較低位設定為1
會把x最右邊1及較低位都設定為1,即將最右邊1設定為0
如果, 則x為2的n次冪
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <= 0) return false;
return (n & (n - 1)) == 0;
}
};
時間複雜度
空間複雜度