-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitwiseAndOfNumbersRange.cpp
58 lines (53 loc) · 1.07 KB
/
BitwiseAndOfNumbersRange.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//
// Created by Ally Wang on 18/04/15.
// Copyright (c) 2015 Ally Wang. All rights reserved.
//
#include <iostream>
using namespace std;
int rangeBitwiseAnd(int m, int n)
{
int res=0;
if(m == n) return m;
int diff = n-m; // determine the highest bit that can be common on 1 in the numbers between m and n
for(int i = 30; i > 0; --i)
{
int a = 1<<i;
if(n >= a && a >= diff)
{
n = n -a;
if(m >= a)
{
m = m -a;
res +=a;
}
}
}
return res;
}
string convertToBinary(int x)
{
string s;
for(int i=0; i < 32; ++i)
{
int tmp = x>>i & 1;
s.push_back(tmp+'0');
}
reverse(s.begin(), s.end());
return s;
}
int main(int argc, const char * argv[]) {
// insert code here...
int m, n;
cout << "please input two positive number as range: " << endl;
cin >> m >> n;
if(m >n) swap(m,n);
cout << "binary in order: " << endl;
for(int i = m; i <= n; ++i)
{
string s = convertToBinary(i);
cout << s << endl;
}
int res = rangeBitwiseAnd(m,n);
cout << "Bitwise AND between " << m << " and " << n << " is: " << res << endl;
return 0;
}