9ms C++ concise solution


  • 0
    C
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            string res = "";
            int carry = 0;
            for(int i = num1.size() - 1, j = num2.size()- 1; i >= 0 || j >= 0; --i, --j){
                int a = i >= 0 ? int(num1[i] - '0') : 0;
                int b = j >= 0 ? int(num2[j] - '0') : 0;
                int tmp = a + b + carry;
                res = (char) (tmp % 10 + '0') + res;
                carry = tmp >= 10;
            }
            if(carry == 1) res = '1' + res;
            return res;
        }
    };
    

Log in to reply
 

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