43. Multiply Strings(Leetcode每日一题-2020.08.13)

Problem

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note:

  • The length of both num1 and num2 is < 110.
  • Both num1 and num2 contain only digits 0-9.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

Example1

Input: num1 = “2”, num2 = “3”
Output: “6”

Example2

Input: num1 = “123”, num2 = “456”
Output: “56088”

Solution

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 -- ) //将nums1中的每个数字倒序放入A
            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 -- ;//去除前导0

        string res;
        while (k >= 0) res += C[k -- ] + '0';

        return res;
    }
};

你可能感兴趣的:(leetcode字符串,leetcode数学)