I'm trying to write an algorithm for a larger project that will take two strings which are both large integers (only using 10 digit numbers for the sake of this demo) and add them together to produce a final string that accurately represents the sum of the two original strings. I realize there are potentially better ways to have gone about this from the beginning but I am supposed to specifically use strings of large integers as opposed to a long integer.

My thinking was to take the two original strings, reverse them so their ones position, tens position, and so on all line up properly for adding. Then one position at a time, convert the characters from the strings to single integers and add them together and then use that sum as the ones position or otherwise for the final string, which once completed will also be reversed back to the correct order of characters.

Where I'm running into trouble I think is in preparing for the event in which the two integers from the corresponding positions in their strings add to a sum greater than 9, and I would then have carry over some remainder to the next position. For example, if I had 7 and 5 in my ones positions that would add to 12, so I would keep the 2 and add 1 to the tens position once it looped back around for the tens position operation.

I'm not getting results that are in any way accurate and after spending a large amount of time stumbling over myself trying to rectify my algorithm, I am not sure what I need to do to fix this.

Hopefully my intended process is clear and someone will be able to point me in the right direction or correct some mistake I may have in my program.

Thanks in advance.

    #include <iostream>
    #include <cstdlib>
    #include <string>


    using namespace std;


    int main ()
    {
        string str1 = "1234567890", str2 = "2345678901"; //Two original strings of large integers
        string rev_str1, rev_str2;
        int int1 = 0, int2 = 0;
        string final; //Final product string, sum of two original strings
        int temp_int = 0, buffer_int, remainder = 0;
        string temp_str = "", buffer_str;
        char buffer[100] = {0};


        cout << "str1 = " << str1 << endl;
        cout << endl;
        cout << "str2 = " << str2 << endl;
        cout << endl;


        rev_str1 = string(str1.rbegin(), str1.rend());


        rev_str2 = string(str2.rbegin(), str2.rend());


        for (int i = 0; i < 10; i++)
        {
            buffer_str = rev_str1.at(i);


            int1 = atoi(buffer_str.c_str());


            buffer_str = rev_str2.at(i);


            int2 = atoi(buffer_str.c_str());


            buffer_int += (int1 + int2 + remainder);


            remainder = 0;


            while (buffer_int > 9)
            {
                buffer_int -= 10;


                remainder += 10;
            }


            temp_str = itoa(buffer_int, buffer, 10);


            final += temp_str;
        }


        final = string(final.rbegin(), final.rend());


        cout << "final = " << final << endl;


        cout << endl;
    }

Recommended Answers

All 2 Replies

You will also have a challenge if the two inputs are of different length.
First make the strings the same length by adding zeros to the most significant digit.
Create a int carry variable
Them get chat at index of each input.
Convert those to digits.
add two together.
If greater than 9, set carry, subtract 10, convert remainder to char and append to the result string

Let me know if this helps

As gkbush said, you first need to make sure that the strings have even length. Here's a simple function that might help you:

void getEven(string &str1, string &str2){
    if (str1.size()==str2.size()) return;
    else if (str1.size()<str2.size()) while (str1.size()!=str2.size()) str1.push_back('0');
    else while (str2.size()!=str1.size()) str2.push_back('0');
}

This will add '0''es to the smaller string.

As for the adding part (considering only positive numbers here), a simple for is more than enough:

    //reverse the strings + make their length the same + verify that contains only digits
    string both;
    int carry = 0;
    for (int i = 0;i < (int)nr1.size();i++){
        int sum = (nr1[i] - '0') + (nr2[i] - '0') + carry; //the sum
        if (sum>9) {
            sum -= 10;
            carry = 1;
        }
        else carry = 0;
        both.push_back('0' + sum);
    }
    if (carry==1) both.push_back('1');
    both = string(both.rbegin(), both.rend()); //the result

Now wrap this code into a function (making the correct validation and input correction) and you're redy to go.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.