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

<p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> num1 = "2", num2 = "3"
<strong>Output:</strong> "6"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> num1 = "123", num2 = "456"
<strong>Output:</strong> "56088"
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li>
	<li><code>num1</code> and <code>num2</code> consist of digits only.</li>
	<li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li>
</ul>

class Solution {
public:
    string multiply(string num1, string num2) {
        if(num1 == "0" || num2 == "0") return "0";
        string& shorter = num1.size() < num2.size() ? num1 : num2;
        string& longer = num1.size() < num2.size() ? num2 : num1;
        string res = "0";
        string zeros = "";
        for(int i = longer.size() - 1; i >= 0; i--) {
            int cur = longer[i] - '0';
            if(cur > 0) {
                string addend = multiply(shorter, cur);
                addend.append(zeros);
                add(res, addend);
            }
            zeros += '0';
        }
        return res;
    }

private:
    string multiply(const string& s1, int num) {
        int carry = 0;
        string ret;
        for(int i = s1.size() - 1; i >= 0; i--) {
            int cur = s1[i] - '0';
            int res = cur * num + carry;
            ret = char('0' + res % 10) + ret;
            carry = res / 10;
        }
        if(carry > 0) {
            ret = char('0' + carry) + ret;
        }
        return ret;
    }

    void add(string& s1, string& s2) {
        int l1 = s1.length() - 1, l2 = s2.length() - 1;
        int carry = 0;
        while(l1 >= 0 || l2 >= 0 || carry > 0) {
            int n1 = l1 >= 0 ? s1[l1] - '0' : 0;
            int n2 = l2 >= 0 ? s2[l2--] - '0' : 0;
            int res = n1 + n2 + carry;
            carry = res / 10;
            char c = (res % 10) + '0';
            if(l1 >= 0) {
                s1[l1--] = c;
            }
            else {
                s1 = c + s1;
            }
        }
    }
};
24418