数字以相反的顺序存储在数组中。以下功能应添加两个数字a
和b
,并将总和存储在result
中:
public static void SumDigitArraysDifferentSize(int[] a, int[] b, int[] result)
{
int length = Math.Max(a.Length, b.Length);
for (int i = 0; i < length; i++)
{
int lhs = (i < a.Length) ? a[i] : 0;
int rhs = (i < b.Length) ? b[i] : 0;
result[i] = (result[i] + lhs + rhs) % 10;
int carry = (result[i] + lhs + rhs) / 10;
for (int j = 1; carry > 0; j++)
{
result[i + j] = (result[i + j] + carry) % 10;
carry = (result[i + j] + carry) / 10;
}
}
}
但是,如果我添加例如:
static void Main(string[] args)
{
int[] lhs = { 9 }
int[] rhs = { 9, 9 };
int size = Math.Max(lhs.Length, rhs.Length) + 1;
int[] result = new int[size];
SumDigitArraysDifferentSize(lhs, rhs, result);
PrintArray(result);
}
结果是:
{ 8, 1, 1 }
而不是预期的:
{ 8, 0, 1 }
对于MCVE:
public static void PrintArray(int[] Array)
{
Console.Write("{");
int length = Array.Length;
for (int i = 0; i < length; i++)
{
Console.Write(Array[i]);
if (i < length - 1)
{
Console.Write(", ");
}
}
Console.Write("}\n");
}
答案 0 :(得分:2)
您正在分配result[i]
,并在计算carry
时再次使用结果。
此:
result[i] = (result[i] + lhs + rhs) % 10;
int carry = (result[i] + lhs + rhs) / 10;
应该是:
var sum = result[i] + lhs + rhs;
result[i] = (sum) % 10;
int carry = (sum) / 10;
同样适用于for (int j = 1; ...)
。
答案 1 :(得分:0)
为了完整起见,以下是评论部分(@Lasse V. Karlsen)提议的结果
public static void SumDigitArrays(int[] a, int[] b, int[] result)
{
int length = Math.Max(a.Length, b.Length);
for (int i = 0; i < length; i++)
{
int lhs = (i < a.Length) ? a[i] : 0;
int rhs = (i < b.Length) ? b[i] : 0;
int sum = result[i] + lhs + rhs;
result[i] = sum % 10;
int carry = sum / 10;
result[i + 1] = result[i + 1] + carry;
}
}