给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"输出: "100"
示例 2:
输入: a = "1010", b = "1011"输出: "10101"
public string AddBinary(string a, string b) {
StringBuilder res = new StringBuilder();
int aLen = a.Length;
int bLen = b.Length;
int up = 0;
int index = 0;
int temp = 0;
while(index < aLen || index < bLen)
{
temp = 0;
if(index < aLen)
{
temp += a[aLen - index - 1] - '0';//转化为数字0和1
}
if(index < bLen)
{
temp += b[bLen - index - 1] - '0';//转换为数字0和1
}
temp += up;//加上进位值
up = temp / 2;//是否进位
temp = temp % 2;//当前位置的值
res.Insert(0,(char)(temp + '0'));
index++;//向前推进
}
if(up > 0)
{
res.Insert(0,'1');//最后处理没处理到的进位
}
return res.ToString();
}