给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = “11”, b = “1”
输出: “100”
示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”
C#语言实现
public static string AddBinary(string a, string b)
{
if (a.Length < b.Length)
{
string c = a;
a = b;
b = c;
}
int[] result = new int[a.Length + 1];
for (int i = 0; i < a.Length; ++i)
{
int position1 = a.Length - 1 - i;
int position2 = b.Length - 1 - i;
if (position2 >= 0)
{
result[i] += a[position1] + b[position2] - 96;
}
else
{
result[i] += a[position1] - 48;
}
if (result[i] > 1)
{
result[i + 1] += result[i] / 2;
result[i] = result[i] % 2;
}
}
string str = "";
for (int i = result.Length - 1; i >= 0; --i)
{
if (i != result.Length - 1 || result[i] != 0)
str += result[i].ToString();
}
return str;
}