#Leetcode# 201. Bitwise AND of Numbers Range
https://leetcode.com/problems/bitwise-and-of-numbers-range/
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7] Output: 4
Example 2:
Input: [0,1] Output: 0
代码:
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int cnt = 0;
while(m != n) {
m /= 2;
n /= 2;
cnt ++;
}
return (n << cnt);
}
};
找到 $m$ 到 $n$ 之间的左右数字公共的最左边 一直左移(相当于除 $2$)直到 $n$ 和 $m$ 相等 记录下移动的位数然后结果是移回去的数字

浙公网安备 33010602011771号