我正在尝试实现一个函数来添加两个存储在字符串中的过大(比如说 1000 位长)数字。我在正确转换时遇到问题,因此我可以正确添加数字。
到目前为止,这就是我所做的:
string addBegin (string low, string high, int diff)
{
for (int i = 0; i <= diff; i++)
low = "0" + low;
high = "0" + high;
cout << "low: " << low << "\nhigh: " << high << endl;
string result;
int sum, carry = 0;
for (int i = low.length()-1; i >= 0; i--)
{
sum = (int)low[i] + (int)high[i] + carry;
carry = 0;
if (sum > 9)
{
sum -= 10;
carry = 1;
}
result = to_string(sum) + result;
}
return result;
}
string add (string a, string b)
{
int diff = a.length() - b.length();
if (diff <= 0) return addBegin(a, b, abs(diff));
else return addBegin(b, a, diff);
}
int main (void)
{
string x = add("52","205");
cout << "result: " << x << endl;
return 0;
}
输出:
low: 0052
high: 0205 //the first zero is for potential carry
result: 87899293 //wrong, should be 0257
这里的结果由 4 个数字组成:87
、89
和。这显然是错误的,我对 ASCII 值做了一些不需要的添加。任何想法如何使这项工作?或者,是否有某种可笑的简单方法来添加两个非常长的数字?92
93