[leetcode Q43] Multiply String

1. 问题

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.

2. 思路

大整数乘法思路,实现竖式乘法运算即可。

3. 实现

class Solution {
public:
    string multiply(string num1, string num2) {
        int len1 = num1.size();
        int len2 = num2.size();
        int len = len1 + len2;
        string res(len, '0');
        int bit1, bit2, pre, cur;

        for (int i = len1 - 1; i >= 0; i--) {
            bit1 = num1[i] - '0';
            for (int j = len2 - 1, k = len2 + i; j >= 0; j--, k--) {
                bit2 = num2[j] - '0';
                cur = res[k] - '0' + bit1 * bit2;
                res[k] = cur%10 + '0';              // 更新当前位 k
                pre = res[k - 1] - '0' + cur/10;    // 表示进位数
                res[k - 1] = pre % 10 + '0';        // 更新前一位 k - 1
                if (pre >= 10) 
                    res[k - 2] = res[k - 2] + pre/10;
            }
        }
        int x = 0;
        while (res[x] == '0')
            x++;
        if (res.substr(x, len - x) == "")
            return "0";
        return res.substr(x, len - x);
    }
};

你可能感兴趣的:(LeetCode,String,大整数除法)