Skip to content

Commit 03071a8

Browse files
authored
Merge pull request #3 from Chayandas07/Chayandas07-patch-3
Create 27 NOV 27 November Add Binary Strings
2 parents af149e1 + 6143406 commit 03071a8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

27 NOV 27 November Add Binary Strings

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution{
2+
public:
3+
string addBinary(string A, string B)
4+
{
5+
string res;
6+
7+
int i = A.length() - 1;
8+
9+
int j = B.length() - 1;
10+
11+
int carry = 0;
12+
13+
while(i >= 0 || j >= 0){
14+
15+
int sum = carry;
16+
17+
if(i >= 0) sum += A[i--] - '0';
18+
19+
if(j >= 0) sum += B[j--] - '0';
20+
21+
carry = sum > 1 ? 1 : 0;
22+
23+
res += to_string(sum % 2);
24+
25+
}
26+
27+
if(carry) res += to_string(carry);
28+
29+
reverse(res.begin(), res.end());
30+
31+
i = 0;
32+
33+
while(res[i] == '0')
34+
35+
{
36+
37+
res.erase(0, 1);
38+
39+
}
40+
41+
42+
43+
return res;
44+
}
45+
};

0 commit comments

Comments
 (0)