1

我正在尝试实现一个函数来添加两个存储在字符串中的过大(比如说 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 个数字组成:8789和。这显然是错误的,我对 ASCII 值做了一些不需要的添加。任何想法如何使这项工作?或者,是否有某种可笑的简单方法来添加两个非常长的数字?9293

4

3 回答 3

5
    sum = (int)low[i] + (int)high[i] + carry;

This adds the values of the character encodings in e.g. ASCII. You want to subtract '0' from the encoding to get the numeric value.

    sum = low[i] - '0' + high[i] - '0' + carry;
于 2013-05-25T02:05:51.360 回答
4

做数学时不要忘记减去'0'low[i]high[i]

(int)low[i]0x30..对于0x39字符'0'...'9'

于 2013-05-25T02:03:52.910 回答
1

A problem is that you use

sum = (int)low[i] + (int)high[i] + carry;

which should be

sum = low[i] - '0' + high[i] - '0' + carry;
于 2013-05-25T02:09:28.490 回答