Leetcode 201. Bitwise AND of Numbers Range

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Bitwise AND of Numbers Range

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int mask = INT_MAX;
while((m & mask) != (n & mask)) {
mask <<= 1;
}
return m & mask;
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int count = 0;
while(m != n) {
m >>= 1;
n >>= 1;
count++;
}
return m << count;
}
};
  • Version 3
1
2
3
4
5
6
7
8
9
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
while(m < n) {
n &= n - 1;
}
return n;
}
};

Reference

  1. https://leetcode.com/problems/bitwise-and-of-numbers-range/description/
如果有收获,可以请我喝杯咖啡!