给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
答案:
public static string AddBinary(string a, string b)
{
int carry = 0;
string s = "";
int index = 0;
while (index<a.Length||index<b.Length||carry>0)
{
int ax = index < a.Length && a[a.Length - index - 1] == '1' ? 1 : 0;
int bx = index < b.Length && b[b.Length - index - 1] == '1' ? 1 : 0;
int digit = ax + bx + carry;
carry = digit > 1 ? 1 : 0;
digit = digit % 2;
s = digit + s;
index++;
}
return s;
}