public class Solution
{
public string AddBinary(string a, string b)
{
Stack<char> resultStack = new();
// 模拟加法计算
int i = a.Length - 1, j = b.Length - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry != 0)
{
// 获取待加数位
int aBit = 0, bBit = 0;
if (i >= 0 && a[i] == '1') aBit = 1;
if (j >= 0 && b[j] == '1') bBit = 1;
// 计算本位和进位
int add = aBit + bBit + carry;
carry = add / 2;
resultStack.Push(
int.IsEvenInteger(add) ? '0' : '1');
// 移至下一位
i--; j--;
}
return new string(resultStack.ToArray());
}
}
LCR 002. 二进制字符串求和
最新推荐文章于 2024-06-14 05:44:12 发布