大数问题-相加和相乘

Multiply Strings No.43

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) {
        
    }
};

我的解法是每次提取num2的一位,然后和num1相乘,所得结果并入string res中,这样虽然每次都要新定义一个string,效率略低,但是思路比较清晰:把字符串相乘划分成了“字符串和数字相乘” 和 “字符串相加” 两个子问题,分别解决就可以。

处理时先将num1,和num2逆序,使得最低位在[0] 位置,这样处理起来比较方便,不易写错。

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1.length() == 0 || num2.length() == 0)
            return "";
        if(num1.length() == 1 && num1[0] == '0') return "0";
        if(num2.length() == 1 && num2[0] == '0') return "0";
        string res(num1.length() + num2.length(), '0');
        int i = 0, j = 0;
        reverse(num1.begin(), num1.end());
        reverse(num2.begin(), num2.end());
        for(i = 0; i < num2.length(); ++i){
            int offset = i;
            string tmp(offset + num1.length() + 1, '0');
            int add = 0;
            for(j = 0; j < num1.length(); ++j){
                int tmpMul = (num1[j] - '0') * (num2[i] - '0') + add;
                add = tmpMul / 10;
                tmp[j + offset] = (tmpMul % 10) + '0';
            }
            tmp[j + offset] = add + '0';
            plus(res, tmp);
        }
        int countStartZero = 0; //高位'0'的个数
        for(i = res.length() - 1; i >= 0 && res[i] == '0'; --i, ++countStartZero);
        if(countStartZero == res.length()) return "0";
        res = res.substr(0, res.length() - countStartZero);
        reverse(res.begin(), res.end());
        return res;
    }
private:
    void plus(string &s1, string &s2){
        int add = 0;
        for(int i = 0; i < s1.length() && (add > 0 || i < s2.length()); ++i){
            int tmp = (s1[i] - '0') + add;
            if(i < s2.length()) tmp += (s2[i] - '0');
            add = tmp / 10;
            s1[i] = (tmp % 10) + '0';
        }
    }
};
    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/Algebra2016/article/details/78010063
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞