C++ Solution easy to read


  • 0
    I
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            string addString = "";
            int carry = 0;
            
            for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0 || carry > 0;)
            {
                int sum = 0;
                if (i >= 0)
                {
                    sum += (int)(num1[i] - '0');
                    i--;
                }
                if (j >= 0)
                {
                    sum += (int)(num2[j] - '0');
                    j--;
                }
                if (carry > 0)
                {
                    sum += carry;
                }
                int digitSum = sum % 10;
                addString = to_string(digitSum)+ addString;
                
                if (sum / 10 == 1)
                {
                    carry = 1;
                }
                else 
                {
                    carry = 0;
                } 
            }
            
            return addString;
        }
    };
    

Log in to reply
 

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