-
Notifications
You must be signed in to change notification settings - Fork 0
/
5_5.cpp
67 lines (61 loc) · 1.01 KB
/
5_5.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
59
60
61
62
63
64
65
66
67
//
// 5_4.cpp
//
//
// Created by Pengyan Qin on 7/3/15.
//
//
#include <iostream>
#include <vector>
using namespace std;
void print(int n){
vector<int> v;
int count = 0;
while(count < 32){
if(n & 1)
v.push_back(1);
else
v.push_back(0);
count++;
n >>= 1;
}
while(!v.empty()){
cout << v.back();
v.pop_back();
}
cout << endl;
}
// using XOR
int numofbits(int a, int b){
int res = a^b;
int count = 0;
int bit = 0;
while(bit < 32){
if(res & 1)
count++;
res >>= 1;
bit++;
}
return count;
}
// compare bit by bit
int numofbits1(int a, int b){
int count = 0;
int bit = 0;
while(bit < 32){
if((a&1) != (b&1))
count++;
a >>= 1;
b >>= 1;
bit++;
}
return count;
}
int main(){
int a = 32;
print(a);
int b = 24;
print(b);
cout << numofbits(a, b) << endl;
cout << numofbits1(a, b) << endl;
}