43. Multiply Strings

1. Question:

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

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

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

2. Solution

C++ code

执行时间:4ms

class Solution {
public:

    void mult(int a, string num,int *p,int size)
    {
        int lastIndex = size - 1;
        int index = num.size()-1;
        int step = 0;
        while (index >= 0)
        {    
            int curValue = a * (int(num[index]) - 48) + step;
            step = curValue / 10;
            curValue = curValue - 10 * step;
            
            p[lastIndex] = curValue;
            lastIndex -= 1;
            index -= 1;
        }
        
        p[lastIndex] = step;
        lastIndex -= 1;
        p[lastIndex] = -1;
    }

    void initPoint(int * p, int size, int initValue)
    {
        for (int i = 0; i < size; i++)
        {
            p[i] = initValue;
        }
    }

    void printPoint(int *p, int size)
    {
        for (int i = 0; i < size; i++)
        {
            cout << p[i];
        }
    }

    void addPoint(int *p1, int * p2, int size,int step_bit)
    {
        int p1_index = size - 1;
        int step = 0;
        int cur = 0;
        while (p1_index >= 0 && p1[p1_index] != -1)
        {    
            cur = p2[p1_index-step_bit] +p1[p1_index] + step;
            step = cur / 10;
            cur -= step * 10;
            p2[p1_index - step_bit] = cur;
            p1_index -= 1;
        }
    }
    string multiply(string num1, string num2) {
        if (num1 == "0" or num2 == "0") {
            return "0";
        }
        int len1 = num1.size();
        int len2 = num2.size();
        int re_size = len1 + len2 + 2;
        int * p1 = new int[re_size];
        int * p2 = new int[re_size];
        initPoint(p1, re_size, -1);
        initPoint(p2, re_size, 0);
        

        int p1_index = len1 - 1;
        int step_bit = 0;
        while (p1_index >= 0)
        {
            mult(num1[p1_index] - 48, num2, p1, re_size);
            addPoint(p1, p2, re_size, step_bit);
            step_bit += 1;
            p1_index -= 1;
        }

        string re = "";
        int i = 0;
        while (p2[i] == 0) {
            i++;
        }
        while (i < re_size) {
            re += to_string(p2[i]);
            i++;
        }
        return re;
    }
};
原文地址:https://www.cnblogs.com/ordili/p/10339175.html