c# - 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
带有加号/减号运算符的 a ,并且不确定这些行实现了什么。
脚注 - 二进制计算看起来是正确的
解决方案
推荐阅读
- android - SVG 图像未显示在简单的 android cordova 表中
- webview - webview 中的视频在第二次运行时不起作用
- javascript - 多次调用另一个js文件的generator函数并与generators同步运行
- node.js - 如何检查 ExpressJS server.js 中的 React 路由?
- python-3.x - Python:总结列表中所有具有相同teamA和teamB的dicts的score1和score2字段?
- c - 根据条件移动矩阵列
- oracle - Artifactory 可以使用 Oracle RAC 吗?如果是,那么支持哪些 Oracle 版本和版本?
- asp.net-mvc - MVC 在索引视图中更改日期格式
- c++ - 错误:没有用于初始化 ... 和 mexFunction 的匹配构造函数
- python - How to apply math.ceil function to the part of objective function in python pulp