43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly

常规计算,一个被乘数,一个乘数

class Solution {
public:
    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) {                //npos是一个常数,用来表示不存在的位置,
            return sum.substr(startpos);               //截取有效位 
        } 
        return "0";
    }
};
原文地址:https://www.cnblogs.com/hozhangel/p/7881282.html