Saraph
Saraph

Reputation: 1002

Adding two strings arithmetically

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?

Upvotes: 1

Views: 1087

Answers (3)

jmihalicza
jmihalicza

Reputation: 2089

Do not forget subtracting '0' from low[i] and high[i] when doing the math.

(int)low[i] is 0x30..0x39 for chars '0'..'9'.

Upvotes: 4

kaitian521
kaitian521

Reputation: 578

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;

Upvotes: 1

Potatoswatter
Potatoswatter

Reputation: 137780

    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;

Upvotes: 5

Related Questions