在处理大量数字时,最基本的设计决策之一可能是如何代表大量数字?
它是字符串,数组,列表还是自定义(本地)存储类。
做出决定后,可以将实际的数学运算分解成较小的部分,然后使用本地语言类型(例如int或integer)执行。
我在C#.Net中包含了一个非常基本的 ADDITION示例,该示例将生成的大数字存储为字符串。传入的“数字”也是字符串,因此一个人应该能够发送非常“大”的数字。请记住,为简单起见,该示例仅适用于整数。
即使使用字符串,字符数或数字中的“数字”也有限制,如下所示:
.NET字符串的最大可能长度是多少?
但是您可以添加一些非常大的数字,远远超出.Net的int32或int64本机类型。
无论如何,这是一个字符串存储实现。
/// <summary>
/// Adds two "integers". The integers can be of any size string.
/// </summary>
/// <param name="BigInt1">The first integer</param>
/// <param name="BigInt2">The second integer</param>
/// <returns>A string that is the addition of the two integers passed.</returns>
/// <exception cref="Exception">Can throw an exception when parsing the individual parts of the number. Callers should handle. </exception>
public string AddBigInts(string BigInt1, string BigInt2)
{
string result = string.Empty;
//Make the strings the same length, pre-pad the shorter one with zeros
int length = (BigInt1.Length > BigInt2.Length ? BigInt1.Length : BigInt2.Length);
BigInt1 = BigInt1.PadLeft(length, '0');
BigInt2 = BigInt2.PadLeft(length, '0');
int remainder = 0;
//Now add them up going from right to left
for (int i = (BigInt1.Length - 1); i >= 0; i--)
{
//If we don't encounter a number, this will throw an exception as indicated.
int int1 = int.Parse(BigInt1[i].ToString());
int int2 = int.Parse(BigInt2[i].ToString());
//Add
int add = int1 + int2 + remainder;
//Check to see if we need a remainder;
if (add >= 10)
{
remainder = 1;
add = add % 10;
}
else
{
remainder = 0;
}
//Add this to our "number"
result = add.ToString() + result;
}
//Handle when we have a remainder left over at the end
if (remainder == 1)
{
result = remainder + result;
}
return result;
}
我希望这会给您一些有关您自己的实现的想法。请注意,示例代码可能未经过优化或类似的处理。它旨在给出一些如何实现的想法。