LC 415. Add Strings

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
public:
    string addStrings(string num1, string num2) {
        if(num1.size()>num2.size()){
            swap(num1,num2);
        }
        int n1 = num1.size();
        int n2 = num2.size();
        reverse(num1.begin(),num1.end());
        reverse(num2.begin(),num2.end());
        int carry = 0,sum = 0,ans = 0;
        string res = "";
        for(int i=0;i<n1;i++){
            sum = (num1[i]-'0') + (num2[i]-'0') + carry;
            ans = sum%10;
            carry = sum/10;
            res.push_back(ans+'0');
        }
        for(int i=n1;i<n2;i++){
            sum = num2[i] - '0' + carry;
            ans = sum%10;
            carry = sum/10;
            res.push_back(ans+'0');
        }
        if(carry){
            res.push_back(carry + '0');
        }
        reverse(res.begin(),res.end());
        return res;
    }
};


Dicussion Forum