LeetCode 201 Bitwise AND of Numbers Range 位运算 难度:0

时间:2023-03-08 18:04:05

https://leetcode.com/problems/bitwise-and-of-numbers-range/

[n,m]区间的合取总值就是n,m对齐后前面一段相同的数位的值

比如

5:101

7:111

结果就是

4:100

class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int len = 0;
long long tmp = 1;
for(;tmp <= n || tmp <= m;len++){tmp<<=1;}
int ans = 0;
for(int i = len - 1;i>=0;i--){
if(((1<<i) & n) == ((1<<i) & m))ans |= (1<<i)&m;
else break;
}
return ans;
}
};