-
Notifications
You must be signed in to change notification settings - Fork 0
/
16_add_binary.cpp
134 lines (122 loc) · 2.96 KB
/
16_add_binary.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <iostream>
using namespace std;
int reverse(int num)
{
int ans = 0;
while (num > 0)
{
int lastdigit = num % 10;
ans = ans * 10 + lastdigit;
num /= 10;
}
return ans;
}
void add_binary(int a, int b)
{
int ans = 0;
int prev_carry = 0;
while (a > 0 && b > 0)
{
// when digit of both binary is zero
if (a % 10 == 0 && b % 10 == 0)
{
// with prev carry
if (prev_carry == 1)
{
ans = ans * 10 + 1;
prev_carry = 0;
}
// without prev carry
else
{
ans = ans * 10 + 0;
}
}
// when digit of one of the binary is zero and other is one
else if ((a % 10 == 1 && b % 10 == 0) || (a % 10 == 0 && b % 10 == 1))
{
// with prev carry
if (prev_carry == 1)
{
ans = ans * 10 + 0;
prev_carry = 1;
}
// without prev carry
else
{
ans = ans * 10 + 1;
}
}
// when digit of both binary is one
else if (a % 10 == 1 && b % 10 == 1)
{
// with prev carry
if (prev_carry == 1)
{
ans = ans * 10 + 1;
}
// without prev carry
else
{
ans = ans * 10 + 0;
}
prev_carry = 1;
}
a /= 10;
b /= 10;
}
// if any of the binary number has more digits
while (a > 0)
{ // for first binary number
// with previous carry
if (prev_carry == 1)
{
if (a % 10 == 1)
{
ans = ans * 10 + 0;
prev_carry = 1;
}
else
{
ans = ans * 10 + 1;
prev_carry = 0;
}
}
// without previous carry
else
ans = ans * 10 + a % 10;
a /= 10;
}
while (b > 0)
{ // for second binary number
// with previous carry
if (prev_carry == 1)
{
if (b % 10 == 1)
{
ans = ans * 10 + 0;
prev_carry = 1;
}
else
{
ans = ans * 10 + 1;
prev_carry = 0;
}
}
// without previous carry
else
ans = ans * 10 + b % 10;
b /= 10;
}
// if a carry is left than extra most significant bit of 1 is added
if (prev_carry == 1)
ans = ans * 10 + 1;
// now we got a answer which is reverse so we need to reverse the number.
cout << reverse(ans) << endl;
return;
}
int main()
{
// add_binary(10101,11010);
return 0;
}