题目描述
https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/
分析
5: 0000 01016: 0000 01107: 0000 0111====================共同前缀0000 0100********************9: 0000 100110:0000 101011:0000 1011===================共同前缀0000 0100
其实就时查找最大共同前缀。
答案
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int shift = 0;
// 找到公共前缀
while (m < n) {
m >>= 1;
n >>= 1;
++shift;
}
return m << shift;
}
};
