王廷瑋|數位醫療|智慧醫療: 201. Bitwise AND of Numbers Range WFU

2024年7月12日 星期五

201. Bitwise AND of Numbers Range

201. Bitwise AND of Numbers Range


給定兩個整數 left 和 right,表示範圍 [left, right],返回此範圍內所有數字的按位與(包括範圍端點)。

範例:

輸入: left = 5, right = 7 輸出: 4


Python


class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
shift = 0
# Find the common prefix
while left < right:
left >>= 1
right >>= 1
shift += 1
# Shift the common prefix back to the left
return left << shift

16.58MB, 39ms


C++


class Solution {
public:
int rangeBitwiseAnd(int left, int right) {
int shift = 0;
// Find the common prefix
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}
// Shift the common prefix back to the left
return left << shift;
}
};

10.07MB, 4ms


Javascript


/**
* @param {number} left
* @param {number} right
* @return {number}
*/
var rangeBitwiseAnd = function(left, right) {
let shift = 0;
// Find the common prefix
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}
// Shift the common prefix back to the left
return left << shift;
};

55.09MB, 135ms