[LeetCode] 大数问题,相加和相乘,题 Multiply Strings

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

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';

        }

    }

};

 

你可能感兴趣的:(LeetCode)