Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
a =
"11"
b =
"1"
Return
"100"
.class Solution { public: string addBinary(string a, string b) { int lenA = a.length(); int lenB = b.length(); int i = 0; int overflow = 0; string res; while(i<lenA || i<lenB) { int a1 = i<lenA ? a[lenA - 1 - i] - '0' : 0; int a2 = i<lenB ? b[lenB - 1 - i] - '0' : 0; int sum = a1 + a2 + overflow; overflow = sum > 1 ? 1: 0; char c = sum %2 +'0'; res = c + res; i++; } if(overflow) res = '1' + res; return res; } };