一道面试题(C#实现了超大整数的加减乘法运算)
static void Main(string[] args)
{
String a = "5661819829134871879051910331902406583704611050840296586361716685667708181008762236714628309134558913";
String b = "3411153732148254698742623133189372941607630447158281924926002101211802711589274474153788470764953449";
String rst = null;
Console.WriteLine("请输入您要进行的运算:1--加法;2--减法;3--乘法!");
int flag = int.Parse(Console.ReadLine());
if (flag == 1 || flag == 2)
rst = AccountA(a, b, flag);
else if (flag == 3)
rst = AccountB(a, b, flag);
Console.WriteLine("整数A为:");
Console.WriteLine(a);
Console.WriteLine("整数B为:");
Console.WriteLine(b);
Console.WriteLine("运算结果为:");
Console.Write(rst);
Console.ReadKey();
}
static String AccountB(String strA, String strB, int flag)
{
String rst = null;
int[,] a = new int[strB.Length, strA.Length + strB.Length];
int num1, num2, carry = 0, sum = 0, temp;
int[] s = new int[a.GetLength(1)];
for (int i = 0; i < a.GetLength(0); i++)
for (int j = 0; j < a.GetLength(1); j++)
a[i, j] = 0;
for (int i = strB.Length - 1; i >= 0; i--)
{
int j = strA.Length - 1;
for (; j >= 0; j--)
{
num1 = int.Parse(strA[j].ToString());
num2 = int.Parse(strB[i].ToString());
temp = num1 * num2 + carry;
a[strB.Length - i - 1, i + j + 1] = temp % 10;
carry = temp / 10;
}
a[strB.Length - i - 1, i + j + 1] = carry;
carry = 0;
}
for (int i = a.GetLength(1) - 1; i > 0; i--)
{
temp = 0;
for (int j = 0; j < a.GetLength(0); j++)
temp += a[j, i];
temp += carry;
s[i] = temp % 10;
carry = temp / 10;
}
s[0] = carry + a[a.GetLength(0) - 1, 0];
for (int i = 0; i < s.Length; i++)
rst += s[i].ToString();
//Code End
return rst;
}
static String AccountA(String strA, String strB, int flag)
{
String rst = null;
String strC = null, strD = null;
char[] a = new char[strA.Length + 1];
int b, c, carry = 0, borrow = 0, temp = 0;
//Code Begin
if (flag == 1)
{
for (int i = strA.Length - 1; i >= 0; i--)
{
b = int.Parse(strA[i].ToString());
c = int.Parse(strB[i].ToString());
temp = b + c + carry;
a[i + 1] = (char)(temp % 10 + 48);
carry = temp / 10;
}
a[0] = (char)(carry + 48);
if (a[0] != '0')
rst += a[0];
else
rst = null;
for (int i = 1; i < a.Length; i++)
rst += a[i];
}
else
{
if (strA.CompareTo(strB) < 0)
{
strC = strB;
strD = strA;
rst += '-';
}
else
{
strC = strA;
strD = strB;
}
for (int i = strC.Length - 1; i >= 0; i--)
{
b = int.Parse(strC[i].ToString());
c = int.Parse(strD[i].ToString());
temp = b - c - borrow;
a[i + 1] = (char)((temp + 10) % 10 + 48);
if (temp < 0)
borrow = 1;
else
borrow = 0;
}
for (int i = 1; i < a.Length; )
if (a[i] == '0' && (rst == '-'.ToString() || rst == null))
i++;
else
{
rst += a[i];
i++;
}
}
return rst;
}
}