Simple C++ Solution


  • 0
    A
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            int i = num1.size()-1;
            int j = num2.size()-1;
            string sum = "";
            int carry = 0;
            while (i>=0 && j>=0) {
                string digit="0";
                digit[0] = (char)('0' + (num1[i]-'0' + num2[j]-'0' + carry) % 10);
                sum = digit + sum;
                carry = (num1[i]-'0' + num2[j]-'0' + carry) / 10;
                i--;
                j--;
            }
            
            while (i>=0) {
                //cout << "num1 " << num1[i] << endl;
                string digit="0";
                digit[0] = (char)('0' + (int)(num1[i]-'0' + carry) % 10);
                //cout << "digit = " << digit << endl;
                sum = digit + sum;
                carry = (num1[i]-'0'+carry) / 10;
                i--;
            }
            
            while (j>=0) {
                string digit="0";
                digit[0] = (char)('0' + (int)(num2[j]-'0' + carry) % 10);
                sum = digit + sum;
                carry = (num2[j]-'0' + carry) / 10;
                j--;
            }
            
            if (carry) sum = "1" + sum;
            return sum;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.