Skip to content

Commit c73ca5a

Browse files
committed
add cpp solution
1 parent 3fd35d6 commit c73ca5a

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public:
3+
string addBinary(string a, string b) {
4+
string ans = (a.length() > b.length())?a:b;
5+
int sum = 0;
6+
for (int i = 0; i < ans.length(); i++){
7+
if (i < a.length()) sum += (a[a.length() - i - 1] == '1')?1:0;
8+
if (i < b.length()) sum += (b[b.length() - i - 1] == '1')?1:0;
9+
ans[ans.length() - i - 1] = (sum & 1) + '0';
10+
sum >>= 1;
11+
}
12+
if (sum == 1) ans = "1" + ans;
13+
return ans;
14+
}
15+
};

0 commit comments

Comments
 (0)