leetcode - 201. 数字范围按位与
题目:
代码:
#include <iostream>
using namespace std;
/*
按位与只要有一位是0,则这个位置一定是0,因为此题可看作是寻找 m与 n的公共前缀
*/
int rangeBitwiseAnd(int left, int right) {
int shift = 0; //记录移动的位数
while(left < right){
left = left >> 1;
right = right >> 1;
shift++;
}
return left << shift;
}
int main(){
int res;
int left, right;
cin>>left>>right;
res = rangeBitwiseAnd(left, right);
cout<<res;
return 0;
}