【发布时间】:2016-08-25 14:11:44
【问题描述】:
我的任务是将一个非常大的数字加到另一个数字上并打印结果。 这是我的实现,它应该给出 1000 作为输出,但它写的是 0000。
它应该如何工作: 如果两个数的长度相等: 剩下的数字 %10 只需 /10 。如果结果的长度大于原始长度,则将最后一个余数添加到输出数组的最后一个元素中。
如果两个数字的长度不同: 对相交部分求和,并将余数(以 temp 为单位)添加到相对补码中。
怎么了?
static int[] SumOfBigNumbers(int[] firstNumber, int[] secondNumber)
{
int temp = 0;
int maxLength = (Math.Max(firstNumber.Length, secondNumber.Length));
int minLength = (Math.Min(firstNumber.Length, secondNumber.Length));
int[] output = new int[maxLength + 1];
//sum of equal part
for (int counter = 0; counter < minLength; counter++)
{
output[counter] = (firstNumber[counter] + secondNumber[counter] + temp) % 10;
temp = (firstNumber[counter] + secondNumber[counter] + temp) / 10;
}
//exceptions add the temp to the bigger array
if (temp!=0)
{
//if first array is bigger than the second
if (firstNumber.Length > secondNumber.Length)
{
for (int i = minLength; i < maxLength + 1; i++)
{
output[i] = (firstNumber[i] + temp) % 10;
temp = (firstNumber[i] + temp) / 10;
}
}
//if second array is bigger than the first
else if (firstNumber.Length < secondNumber.Length)
{
for (int i = minLength; i < maxLength + 1; i++)
{
output[i] = (secondNumber[i] + temp) % 10;
temp = (secondNumber[i] + temp) / 10;
}
}
//if two number has equal length but there is temp left
else
{
output[maxLength] = temp;
}
}
return output;
}
static void Main()
{
int[] firstArray = new int[3] { 0, 0, 5 };
int[] secondArray = new int[3] { 0, 0,5 };
int[] output = SumOfBigNumbers(firstArray, secondArray);
foreach (var i in output)
{
Console.WriteLine(output[i]);
}
}
编辑:如果我复制任务会更好:编写一个计算两个非常长的正整数之和的方法。数字表示为数组数字,最后一位数字存储在索引 0 处的数组中。使该方法适用于长度不超过 10,000 位的所有数字。
【问题讨论】:
-
可能
BigInteger是你正在寻找的东西 -
也许只有我一个人,但我不明白为什么
{0,0,5}+{0,0,5}会导致{1,0,0,0}。如果它在{5,0,0}+{5,0,0}的位置对我来说很有意义。 -
也许我误解了任务。我将其读作第 0 个元素(个)0、第 1 个(十个)元素 0、第 2 个元素(数百个)等等。使用此逻辑,输出应为 0001,稍后可以反转。
-
@Filburt 索引越高,值越显着。
标签: c#