C++ ~6ms two simple loops


  • 0
    M

    It can be nice to do everything in one loop, but the extra conditionals just seem to complicate things for this one. Here are two loops:

            string addStrings(string num1, string num2) {
                if (num1.size() > num2.size()) num1.swap(num2);
    
                auto M = static_cast<int>(num1.size());
                auto N = static_cast<int>(num2.size());
    
                string res;
                int carry = 0;
    
                int i = 1;
                for (; i <= M; ++i) {
                    auto sum = (num1[M - i] - '0') + (num2[N - i] - '0') + carry;
    
                    carry = sum / 10;
                    res += '0' + (sum - 10 * carry);
                }
    
                for (; i <= N; ++i) {
                    auto sum = (num2[N - i] - '0') + carry;
    
                    carry = sum / 10;
                    res += '0' + (sum - 10 * carry);
                }
    
                if (carry)
                    res += '0' + carry;
    
                reverse(begin(res), end(res));
                return res;
            }
    

Log in to reply
 

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