输入两个小数a和b,用字符串表示,满足0<a<1,0<b<1,输出a+b。备注,a和b的小数位数可能会比较大,不能直接转化浮点型进行计算。
static string SDA(string a, string b)
{
int aLength = a.Length, bLength = b.Length;
int minLength = Math.Min(aLength, bLength);
bool isCarry = false;
StringBuilder sb = new StringBuilder(minLength);
for (int i = minLength - 1; i > -1; i--)
{
char tempA = a[i];
if (!char.IsDigit(tempA))
{
sb.Insert(0, tempA);
continue;
}
int tempDigit = (tempA - '0') + (b[i] - '0');
if (isCarry)
++tempDigit;
if (tempDigit > 9)
{
isCarry = true;
sb.Insert(0, tempDigit % 10);
}
else
{
isCarry = false;
sb.Insert(0, tempDigit);
}
}
return sb.ToString() + (minLength == aLength ? b[minLength..] : a[minLength..]);
}
static string SDA2(string a, string b)
{
int aLength = a.Length, bLength = b.Length;
int minLength = Math.Min(aLength, bLength);
bool isCarry = false;
Stack<int> stacks = new Stack<int>(minLength-1);
for (int i = minLength - 1; i > -1; i--)
{
char tempA = a[i];
if (!char.IsDigit(tempA))
{
continue;
}
int tempDigit = (tempA - '0') + (b[i] - '0');
if (isCarry)
++tempDigit;
if (tempDigit > 9)
{
isCarry = true;
stacks.Push(tempDigit % 10);
}
else
{
isCarry = false;
stacks.Push(tempDigit);
}
}
StringBuilder sb = new StringBuilder(minLength);
while (stacks.Count > 0)
{
sb.Append(stacks.Pop());
}
sb.Insert(1, ".");
return sb.ToString() + (minLength == aLength ? b[minLength..] : a[minLength..]);
}
static string SDA3(string a, string b)
{
int aLength = a.Length, bLength = b.Length;
int minLength = Math.Min(aLength, bLength);
bool isCarry = false;
Stack<object> stacks = new Stack<object>(minLength);
for (int i = minLength - 1; i > -1; i--)
{
char tempA = a[i];
if (!char.IsDigit(tempA))
{
stacks.Push(tempA);
continue;
}
int tempDigit = (tempA - '0') + (b[i] - '0');
if (isCarry)
++tempDigit;
if (tempDigit > 9)
{
isCarry = true;
stacks.Push(tempDigit % 10);
}
else
{
isCarry = false;
stacks.Push(tempDigit);
}
}
StringBuilder sb = new StringBuilder(minLength);
while (stacks.Count > 0)
{
sb.Append(stacks.Pop());
}
return sb.ToString() + (minLength == aLength ? b[minLength..] : a[minLength..]);
}
测试
static void Main(string[] args)
{
int aLength = 6000, bLength = 6000;
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
Random random = new Random();
for (int i = 0; i < aLength; i++)
{
a.Append(random.Next(0, 10));
}
a.Insert(0, "0.");
for (int i = 0; i < bLength; i++)
{
b.Append(random.Next(0, 10));
}
b.Insert(0, "0.");
string a1 = a.ToString();
string b1=b.ToString();
// 预加载
Test(SDA2, a1, b1);
Test(SDA, a1, b1);
Test(SDA2, a1, b1);
Test(SDA3, a1, b1);
}
static int n = 0;
static void Test(Func<string, string,string> action,string a,string b)
{
if (n++ == 0)
return;
Stopwatch sw = Stopwatch.StartNew();
sw.Start();
string result3 = action(a, b);
sw.Stop();
//Console.WriteLine(result2);
Console.WriteLine($"耗时:{sw.ElapsedMilliseconds}ms");
}
结果