用C#实现二进制的减法(包括二进制小数)
作为一个大学汪,我开始接触编程。前两天老师让写一个二进制算术编码,于是我遇到了这样一个问题,怎么实现二进制数的减法。熬了两天的夜,写出了下面的代码。若有不对的地方大家海涵…
/// <summary>
/// 构建二进制减法方法
/// </summary>
/// <param name="str">二进制减数</param>
/// <param name="s">二进制被减数</param>
/// <returns>二进制得数</returns>
public string minus(string str, string s)
{
string max = str;
string min = s;
string num = s;
for (int i = s.Length - 1; i >= 0; i--)
{
if (str[i] == '.') { }
else
{
if (i == s.Length - 1)
{
if (max[i] == min[i])
{
num = num.Remove(i, 1);
num += "0";
}
else if (max[i] == '1' && min[i] == '0')
{
num = num.Remove(i, 1);
num += "1";
}
else
{
num = num.Remove(i, 1);
num += "1";
if (str[i - 1] == '.')
{
if (str[i - 2] == '1')
{
max = max.Remove(i - 2, 1);
max = max.Insert(i - 2, "0");
}
else
{
max = max.Remove(i - 2, 1);
max = max.Insert(i - 2, "1");
}
}
else
{
if (str[i - 1] == '1')
{
max = max.Remove(i - 1, 1);
max = max.Insert(i - 1, "0");
}
else
{
max = max.Remove(i - 1, 1);
max = max.Insert(i - 1, "1");
}
}
}
}
else if (i < s.Length - 1 && i > 0)
{
if (str[i + 1] == '0' && s[i + 1] == '1')
{
if (str[i - 1] == '.')
{
if (str[i - 2] == '0')
{
max = max.Remove(i - 2, 1);
max = max.Insert(i - 2, "1");
}
else
{
max = max.Remove(i - 2, 1);
max = max.Insert(i - 2, "0");
}
}
else
{
if (str[i - 1] == '0')
{
max = max.Remove(i - 1, 1);
max = max.Insert(i - 1, "1");
}
else
{
max = max.Remove(i - 1, 1);
max = max.Insert(i - 1, "0");
}
}
if (max[i] == min[i])
{
num = num.Remove(i, 1);
num = num.Insert(i, "0");
}
else
{
num = num.Remove(i, 1);
num = num.Insert(i, "1");
}
}
else
{
if (max[i] == min[i])
{
num = num.Remove(i, 1);
num = num.Insert(i, "0");
}
else if (max[i] == '1' && min[i] == '0')
{
num = num.Remove(i, 1);
num = num.Insert(i, "1");
}
else
{
num = num.Remove(i, 1);
num = num.Insert(i, "1");
if (str[i - 1] == '.')
{
if (str[i - 2] == '1')
{
max = max.Remove(i - 2, 1);
max = max.Insert(i - 2, "0");
}
else
{
max = max.Remove(i - 2, 1);
max = max.Insert(i - 2, "1");
}
}
else
{
if (str[i - 1] == '1')
{
max = max.Remove(i - 1, 1);
max = max.Insert(i - 1, "0");
}
else
{
max = max.Remove(i - 1, 1);
max = max.Insert(i - 1, "1");
}
}
}
}
}
else
{
if (max[i] == min[i])
{
num = num.Remove(i, 1);
num = num.Insert(i, "0");
}
else
{
num = num.Remove(i, 1);
num = num.Insert(i, "1");
}
}
}
}
return num;
}