leetcode-----43. 字符串相乘

  • 链接:https://leetcode-cn.com/problems/multiply-strings/

代码

class Solution {
public:
    string multiply(string num1, string num2) {
        vector A, B;
        int n = num1.size(), m = num2.size();
        for (int i = n - 1; i >= 0; --i) A.push_back(num1[i] - '0');
        for (int i = m - 1; i >= 0; --i) B.push_back(num2[i] - '0');

        vector C(n + m);
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                C[i + j] += A[i] * B[j];
            }
        }
        for (int i = 0, t = 0; i < C.size(); ++i) {
            t += C[i];
            C[i] = t % 10;
            t /= 10;
        }

        int k = C.size() - 1;
        while (k > 0 && !C[k]) k--;
        string ans;
        while (k >= 0) ans += C[k--] + '0';
        return ans;
    }
};

你可能感兴趣的:(leetcode-----43. 字符串相乘)