9ms cpp solution


  • 0
    Z
    #include <string>
    #include <cstdlib>
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            int i = num1.size() - 1;
            int j = num2.size() - 1;
            int carry = 0;
            std::string ret("");
            for (; i >= 0 && j >= 0; --i, --j) {
                char d = sum_char(num1[i], num2[j], carry);
                ret.insert(0, 1, d);
            }
            if (i >= 0) {
                for (; i >= 0; --i) {
                    ret.insert(0, 1, sum_char(num1[i], '0', carry));
                }
            } else if (j >= 0) {
                for (; j >= 0; --j) {
                    ret.insert(0, 1, sum_char('0', num2[j], carry));
                }
            }
            if (carry != 0) {
                ret.insert(0, 1, sum_char('0', '0', carry));
            }
            return ret;
        }
        
        char sum_char(char c1, char c2, int &carry) {
            int n1 = std::atoi(&c1);
            ;
            int n2 = std::atoi(&c2);
            int tmp = n1 + n2 + carry;
            string s = std::to_string(tmp);
            
            if (s.size() > 1) {
                char tmpp = s[0];
                carry = std::atoi(&tmpp);
                return s[1];
            } else {
                carry = 0;
                return s[0];
            }
        }
    };
    

Log in to reply
 

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