首页 > 解决方案 > 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 ,并且不确定这些行实现了什么。

脚注 - 二进制计算看起来是正确的

https://dotnetfiddle.net/Hf0tgx

标签: c#stringbinarycharcalculator

解决方案


推荐阅读