forked from mrigaankzoro/Hacktoberfest24
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Binary
48 lines (42 loc) · 1.28 KB
/
Add Binary
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
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
// Make both strings of equal length by prepending zeros
if(a.size() > b.size())
b = string(a.size() - b.size(), '0') + b;
else if(a.size() != b.size())
a = string(b.size() - a.size(), '0') + a;
string result(a.size(), '0'); // Initialize result string with zeros
bool carry = false; // Initialize carry to false
for(int i = a.size() - 1; i >= 0; --i)
{
if((a[i] == '1' && b[i] == '0') || (a[i] == '0' && b[i] == '1'))
{
result[i] = carry ? '0' : '1';
}
else if(a[i] == '0' && b[i] == '0')
{
result[i] = carry ? '1' : '0';
carry = false;
}
else if(a[i] == '1' && b[i] == '1')
{
result[i] = carry ? '1' : '0';
carry = true;
}
}
if(carry)
result = '1' + result;
return result;
}
};
int main() {
Solution sol;
string a = "1010";
string b = "1011";
cout << sol.addBinary(a, b) << endl; // Output should be "10101"
return 0;
}