C++ 6ms Straightforward Method


  • 0

    You can avoid using reverse() by going from end-index to the front.

    Which adds more complicity in the looping index counting.

    class Solution {
    public:
        string addStrings(string num1, string num2) {
            string shorter = (num1.size() <= num2.size()) ? num1 : num2;
            string longer  = (num1.size() >  num2.size()) ? num1 : num2;
    
            int carry = 0;
            int i = 0;
            
            reverse(shorter.begin(), shorter.end());
            reverse(longer.begin(), longer.end());
            
            for(; i < shorter.size(); ++i) {
                int sum = (shorter[i] - '0') + (longer[i] - '0') + carry;
                carry = sum /10;
                longer[i] = char(sum%10 + '0');
            }
            
            for(; i < longer.size(); ++i) {
                int sum = (longer[i] - '0') + carry;
                carry = sum /10;
                longer[i] = char(sum%10 + '0');
            }
            
            reverse(longer.begin(), longer.end());
    
            if (carry == 1) {
                return "1" + longer;
            } else {
                return longer;
            }
            
        }
    };
    

Log in to reply
 

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