1

I'm trying to implement a function to add two overly large (let's say 1000 digit long) numbers stored in strings. I'm having problems with correct conversions so I can add numbers correctly.

So far, this is what I've done:

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;
}

Output:

low: 0052
high: 0205 //the first zero is for potential carry
result: 87899293 //wrong, should be 0257

The result here is made of 4 numbers: 87, 89, 92 and 93. That is obviously wrong, I did some unwanted additions with ASCII values. Any ideas how to make this work? Or is there, by any chance, some ridiculously simple way to add two veeeeery long numbers?

4

3 に答える 3

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

これにより、ASCII などの文字エンコーディングの値が追加されます。エンコーディングから減算'0'して数値を取得します。

    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

問題は、あなたが使用することです

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

どちらであるべきか

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