Question
Given two binary strings, return their sum (also a binary string).
For example, a = "11" b = "1" Return "100".
My C# Solution
public class Solution {
public string AddBinary(string a, string b) {
var result = string.Empty;
var aLength = a.Length;
var bLength = b.Length;
var carry = 0;
while(aLength > 0 || bLength > 0)
{
var aBit = (aLength > 0)
? Convert.ToInt32(a[aLength - 1].ToString())
: 0;
var bBit = (bLength > 0)
? Convert.ToInt32(b[bLength - 1].ToString())
: 0;
var sum = aBit + bBit + carry;
if (sum > 1)
{
result = (sum % 2) + result;
carry = 1;
}
else
{
result = sum + result;
carry = 0;
}
aLength--;
bLength--;
}
return (carry == 1) ? carry + result : result;
}
}