美文网首页
Multiply Strings And Add Strings

Multiply Strings And Add Strings

作者: _Felix__ | 来源:发表于2019-08-12 15:37 被阅读0次

    43. Multiply Strings

    图解
    string multiply(string num1, string num2) {
        string sum(num1.size() + num2.size(), '0');
        
        for (int i = num1.size() - 1; 0 <= i; --i) {
            int carry = 0;
            for (int j = num2.size() - 1; 0 <= j; --j) {
                int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
                sum[i + j + 1] = tmp % 10 + '0';
                carry = tmp / 10;
            }
            sum[i] += carry;
        }
        
        size_t startpos = sum.find_first_not_of("0");
        if (string::npos != startpos) {
            return sum.substr(startpos);
        }
        return "0";
    }
    

    415. Add Strings

    class Solution {
    public:
    string addStrings(string num1, string num2) {
        int i = num1.size() - 1;
        int j = num2.size() - 1;
        int carry = 0;
        string res = "";
        while(i>=0 || j>=0 || carry){
            long sum = 0;
            if(i >= 0){sum += (num1[i] - '0');i--;}
            if(j >= 0){sum += (num2[j] - '0');j--;}
            sum += carry; 
            carry = sum / 10;
            sum = sum % 10;
            res =  res + to_string(sum);
        }
        reverse(res.begin(), res.end());
        return res;
    }
    };
    

    相关文章

      网友评论

          本文标题:Multiply Strings And Add Strings

          本文链接:https://www.haomeiwen.com/subject/spcujctx.html