Search code examples
c++stringsumcharacterascii

How to get the sum of two strings of numbers - C++


How do I get the sum of two strings that are numbers? For example:

string num1 = "12";
string num2 = "4";

string sum = num1 + num2;

So string sum will equal "16"

How do I do this in c++?

I tried doing it with ascii characters but it does not work I cannot convert the string to an integer as well


Solution

  • To add large integers using string, you can do something like this.

    string doSum(string a, string b)
    {
        if(a.size() < b.size())
            swap(a, b);
    
        int j = a.size()-1;
        for(int i=b.size()-1; i>=0; i--, j--)
            a[j]+=(b[i]-'0');
    
        for(int i=a.size()-1; i>0; i--)
        {
            if(a[i] > '9')
            {
                int d = a[i]-'0';
                a[i-1] = ((a[i-1]-'0') + d/10) + '0';
                a[i] = (d%10)+'0';
            }
        }
        if(a[0] > '9')
        {
            string k;
            k+=a[0];
            a[0] = ((a[0]-'0')%10)+'0';
            k[0] = ((k[0]-'0')/10)+'0';
            a = k+a;
        }
        return a;
    }
    
    int main()
    {
        string result = doSum("1234567890", "123789456123");
        cout << result << "\n";
    }
    

    Output

    125024024013
    

    Reference: See the complete code at Ideone.com