[C++ / O(1) space / O(n) time] Concise Short solution


  • 1
    H
    class Solution {
    public:
        void add (char &a, char b, bool &adv) {
            int val = (a - '0') + (b - '0') + (adv ? 1 : 0);
            if (val < 10) {
                a = '0' + val;
                adv = false;
            } else {
                a = '0' + (val - 10);
                adv = true;
            }
        }
    
        string addStrings(string num1, string num2) {
            string *base = &num1, *adde = &num2;
            if (num2.size() > num1.size()) swap(base, adde);
            
            bool advance = false;
            int i = base->size() - 1, j = adde->size() - 1;
            
            while (j >= 0) add(base->at(i--), adde->at(j--), advance);
            while (i >= 0) add(base->at(i--), '0', advance);
            if (advance) base->insert(base->begin(), '1');
            
            return *base;
        }
    };
    

Log in to reply
 

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