如何解决C# 二进制加法计算器
我正在寻找添加两个二进制字符串的解决方案。我用于证明添加的测试数据:
10 + 1 => 11
1001 + 1 => 1010
1101 + 100 => 10001
10101010 + 11001100 => 101110110
这是我通过谷歌搜索找到的代码:
public static string AddBinary(string a,string b)
{
string result = "";
// Initialize digit sum
int s = 0;
// Traverse both strings starting from last characters
int i = a.Length - 1;
int j = b.Length - 1;
while (i >= 0 || j >= 0 || s == 1)
{
// Compute sum of last digits and carry
s += (i >= 0 ? a[i] - '0' : 0); // if i > 0
s += (j >= 0 ? b[j] - '0' : 0);
// If current digit sum is 1 or 3,add 1 to result
result = (char)(s % 2 + '0') + result;
// Compute carry
s /= 2;
// Move to next digits
i--;
j--;
}
return result;
}
有人可以向我解释一下这三行代码在这里实际上做了什么吗?
s+= (i >= 0 ? a[i] - '0' : 0);
s+= (j >= 0 ? b[j] - '0' : 0);
result = (char)(s % 2 + '0') + result;
我以前从未使用过带有加号/减号运算符的 char
,并且不确定这些行的作用。
脚注 - 二进制计算看起来是正确的
https://dotnetfiddle.net/Hf0tgx
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。