C++ very easy to understand


  • 0
    H
    string addStrings(string num1, string num2) {
            string ans;
            string zeros;
            int carry = 0;
            int tmp = -1;
            bool over = false;
            string longNum = num1;
            string shortNum = num2;
            if (shortNum.length() > longNum.length())
                swap(shortNum, longNum);
            ans.resize(longNum.length(), '0');
            for (int i = 0; i < longNum.length() - shortNum.length(); i++)
                zeros+="0";
            shortNum = zeros+shortNum;      // add zeros
            for (int j = longNum.length() - 1; j >= 0; j--) {
                int dig1 = longNum[j] - '0';
                int dig2 = shortNum[j] - '0';
                tmp = dig1 + dig2 + carry;
                if (tmp >= 10) {
                    carry = 1;
                    tmp = tmp % 10;
                    over = true;
                }
                else {
                    over = false;
                    carry = 0;
                }
                ans[j] = '0' + tmp;
            }
            if (over)
                ans = '1' + ans;
            return ans;
        }
    

Log in to reply
 

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