File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ class Solution {
3+ public:
4+
5+ string addBinary(string a, string b) {
6+
7+
8+ if(b.size() > a.size()) swap(a,b);
9+
10+
11+ while(b.size() < a.size()) b = "0" + b;
12+
13+ int carry = 0;
14+
15+ string res = "";
16+
17+ for(int i = b.size()-1; i >= 0 ; --i)
18+ {
19+
20+ if(b[i] == '1' && a[i]=='1')
21+ {
22+
23+ if(carry == 0) res = "0" + res;
24+
25+ else res = "1" + res;
26+
27+ carry = 1;
28+ }
29+
30+ else if(b[i] =='0' && a[i] =='0')
31+ {
32+
33+ if(carry == 0) res = "0" + res;
34+
35+ else
36+ {
37+ res = "1" + res;
38+ carry = 0;
39+ }
40+ }
41+
42+ else if((b[i]=='0' && a[i]=='1') || (b[i]=='1' && a[i] == '0'))
43+ {
44+
45+ if(carry == 0) res = "1" + res;
46+
47+ else res = "0" + res;
48+
49+ }
50+
51+ }
52+
53+ if(carry == 1) res = "1" + res;
54+
55+ return res;
56+ }
57+ };
You can’t perform that action at this time.
0 commit comments