大整数求和
前言
如果整数过大如何求值,比如说"4654564646547897891", "12315456456454564"
这时候常规整数装不下!
代码
方案一:
public static string bigNumberSum(string bigNumberA, string bigNumberB)
{
int maxLength = bigNumberA.Length > bigNumberB.Length ? bigNumberA.Length : bigNumberB.Length;
int[] arrayA = new int[maxLength+1];
for (var i = 0; i < maxLength+1; i++)
{
if (bigNumberA.Length - 1 - i >= 0)
{
arrayA[i] = bigNumberA[bigNumberA.Length - 1 - i] - '0';
}
else
{
arrayA[i] = 0;
}
}
int[] arrayB = new int[maxLength+1];
for (var i = 0; i < maxLength+1; i++)
{
if (bigNumberB.Length - 1 - i >= 0)
{
arrayB[i] = bigNumberB[bigNumberB.Length - 1 - i] - '0';
}
else
{
arrayB[i] = 0;
}
}
int[] result = new int[maxLength+1];
for (var i = 0; i < maxLength; i++)
{
var temp = result[i];
temp = temp + arrayA[i] + arrayB[i];
if (temp>10)
{
temp = temp - 10;
result[i + 1] = 1;
}
result[i] = temp;
}
var hasup = 1;
if (result[maxLength] == 1)
{
hasup = 0;
}
StringBuilder sb = new StringBuilder();
for (var i = result.Length-1- hasup; i >=0; i--)
{
sb.Append(result[i]);
}
return sb.ToString();
}
static void Main(string[] args)
{
Console.WriteLine(bigNumberSum("465456464654789789", "12315456456454564"));
Console.ReadKey();
}
优化方案二:
九个一组:
public static string bigNumberSum(string bigNumberA, string bigNumberB)
{
int maxLength = bigNumberA.Length > bigNumberB.Length ? bigNumberA.Length : bigNumberB.Length;
var length =Convert.ToInt32(Math.Ceiling(Convert.ToDouble(maxLength) / 9));
int[] arrayA = new int[length];
for (var i = 0; i < length; i++)
{
if (i * 9 + 9 > bigNumberA.Length)
{
if (i * 9 <= bigNumberA.Length-1)
{
arrayA[i] = Convert.ToInt32(bigNumberA.Substring(bigNumberA.Length - 1 - 9 * i-(bigNumberA.Length - i * 9)+1, bigNumberA.Length - i * 9));
}
else
{
arrayA[i] = 0;
}
}
else
{
arrayA[i] = Convert.ToInt32(bigNumberA.Substring(bigNumberA.Length - 1 - 9 * i-9+1, 9));
}
}
int[] arrayB = new int[length];
for (var i = 0; i < length; i ++)
{
if (i * 9 + 9 > bigNumberB.Length)
{
if (i * 9 <= bigNumberB.Length - 1)
{
arrayB[i] = Convert.ToInt32(bigNumberB.Substring(bigNumberB.Length - 1 - 9 * i-(bigNumberB.Length - i * 9)+1, bigNumberB.Length - i * 9));
}
else
{
arrayB[i] = 0;
}
}
else
{
arrayB[i] = Convert.ToInt32(bigNumberB.Substring(bigNumberB.Length-1-9*i-9+1, 9));
}
}
int[] result = new int[length];
for (var i = 0; i < length; i++)
{
result[i] = arrayA[i] + arrayB[i];
}
StringBuilder sb = new StringBuilder();
for (var i = result.Length-1; i >=0; i--)
{
sb.Append(result[i]);
}
return sb.ToString();
}
static void Main(string[] args)
{
Console.WriteLine(bigNumberSum("4654564646547897891", "12315456456454564"));
Console.ReadKey();
}
}