首页 > 解决方案 > 如何在表示为字符串的两个二进制数上模拟减法运算符?

问题描述

static string ReturnValueIfInputOneIsThirteenAndInputLengthIsEqualWithInputTwoLength(string input, string inputTwo)
        {
            string result = "";
            int temp = 0;
            int inputLength = input.Length - 1;
            int inputTwoLength = inputTwo.Length - 1;
            const int two = 2;

            while (inputLength >= 0 || inputTwoLength >= 0 || temp > 0)
            {
                temp += (inputLength >= 0) ? input[inputLength] - '0' : 0;
                temp += (inputTwoLength >= 0) ? inputTwo[inputTwoLength] - '0' : 0;
                result = (char)(temp % two + '0') + result;
                temp /= two;
                inputLength--;
                inputTwoLength--;
            }

            return result.TrimStart('0');
        }

我必须以某种方式模拟表示为字符串的两个二进制数的减法运算符。所以我要求提出一个建议,使这种情况发生而不将它们转换为整数。

例如,如果我输入 101 和 11,结果应该是 10。

这就是我加法的方式,但减法我找不到解决方案。

你有什么建议吗?

标签: c#stringbinarysubtraction

解决方案


推荐阅读