给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1" 输出: "100"
示例 2:
输入: a = "1010", b = "1011" 输出: "10101"
提示:
- 每个字符串仅由字符
'0'
或'1'
组成。 1 <= a.length, b.length <= 10^4
- 字符串如果不是
"0"
,就都不含前导零。
C#代码
public class Solution {
public string AddBinary(string a, string b) {
int num1 = a.Length;
int num2 = b.Length;
int max = Math.Max(num1, num2);
int min = Math.Min(num1, num2);
string c = min == num1 ? a : b;
string d = min == num1 ? b : a;
Stack<int> stack = new Stack<int>();
bool isAdd = false;
int val;
for (int i = min - 1; i > -1; i--)
{
var val1 = c[i];
var val2 = d[i + max - min];
val = val1 ^ val2;
stack.Push(isAdd ? (val ^ 1) : val);
isAdd = val1 == '1' && val2 == '1' || val == 1 && isAdd;
}
for (int i = max - min - 1; i > -1; i--)
{
int.TryParse(d[i].ToString(), out val);
stack.Push(isAdd ? (val ^ 1) : val);
isAdd = d[i] == '1' && isAdd;
}
if (isAdd)
stack.Push(1);
StringBuilder sb = new StringBuilder();
while (stack.Count > 0)
sb.Append(stack.Pop());
return sb.ToString();
}
}