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

代码

class Solution {
public:
    string multiply(string num1, string num2) {
        vector<int> 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<int> 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;
    }
};
posted @ 2020-07-06 16:54  景云ⁿ  阅读(48)  评论(0编辑  收藏  举报