-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_binary2.cpp
94 lines (90 loc) · 1.97 KB
/
add_binary2.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
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
int idx_a=a.size()-1;
int idx_b=b.size()-1;
if(idx_a>idx_b)
{
int diff=idx_a-idx_b;
while(diff)
{
b="0"+b;
diff--;
}
}
if(idx_a<idx_b)
{
int diff=idx_b-idx_a;
while(diff)
{
a="0"+a;
diff--;
}
}
idx_a=a.size()-1;
idx_b=b.size()-1;
bool carry=0;
string result="";
while(idx_a>=0 && idx_b>=0)
{
if(a[idx_a]=='1' && b[idx_b]=='1' && carry==1)
{
result="1"+result;
carry=1;
}
else if(a[idx_a]=='1' && b[idx_b]=='1' && carry==0)
{
result="0"+result;
carry=1;
}
else if(a[idx_a]=='1' && b[idx_b]=='0' && carry==1)
{
result="0"+result;
carry=1;
}
else if(a[idx_a]=='1' && b[idx_b]=='0' && carry==0)
{
result="1"+result;
carry=0;
}
else if(a[idx_a]=='0' && b[idx_b]=='1' && carry==1)
{
result="0"+result;
carry=1;
}
else if(a[idx_a]=='0' && b[idx_b]=='1' && carry==0)
{
result="1"+result;
carry=0;
}
else if(a[idx_a]=='0' && b[idx_b]=='0' && carry==1)
{
result="1"+result;
carry=0;
}
else if(a[idx_a]=='0' && b[idx_b]=='0' && carry==0)
{
result="0"+result;
carry=0;
}
idx_a--;
idx_b--;
}
return (carry==1)?"1"+result:result;
}
};
int main()
{
string a,b;
cout<<"Enter string a : ";
getline(cin,a);
cout<<"Enter string b : ";
getline(cin,b);
Solution s;
cout<<"Result : "<<s.addBinary(a,b)<<endl;
return 0;
}