-
Notifications
You must be signed in to change notification settings - Fork 0
/
200314-1.cpp
36 lines (34 loc) · 843 Bytes
/
200314-1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/
#include <iostream>
using namespace std;
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
unsigned int a = 1;
unsigned int res = 0;
for (int i = 0; i < 32; ++i) {
bool flag = ((m & a) != 0);
if (flag) {
unsigned int next = (m & ~(a - 1)) + a;
if (next <= n) {
flag = false;
}
}
if (flag) {
res |= a;
}
a <<= 1;
}
return (int)res;
}
};
int main()
{
Solution s;
cout << s.rangeBitwiseAnd(5, 7) << endl; // answer: 4
cout << s.rangeBitwiseAnd(0, 1) << endl; // answer: 0
cout << s.rangeBitwiseAnd(0, 2147483647) << endl; // answer: 0
cout << s.rangeBitwiseAnd(2147483647, 2147483647) << endl; // answer: 2147483647
cout << s.rangeBitwiseAnd(2147483646, 2147483647) << endl; // answer: 2147483646
return 0;
}