43. Multiply Strings

package LeetCode_43

/**
 * 43. Multiply Strings
 * https://leetcode.com/problems/multiply-strings/
 * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2,
 * also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

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

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

Constraints:
1. 1 <= num1.length, num2.length <= 200
2. num1 and num2 consist of digits only.
3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
 * */
class Solution {
    /*
    * solution: new array to save the multiplication result of each number, for example: 123*45:
    *   123, index i
    *    45, index j
    * ------
    *    15  index: i+j, i+j+1
    *   10
    *  05
    *   12
    *  08
    * 04
    * ------
    * 01234  new_index
    *
    * Time:O(m*m), Space:O(m+n)
    * */
    fun multiply(num1: String, num2: String): String {
        val m = num1.length
        val n = num2.length
        val array = IntArray(m + n)
        for (i in m - 1 downTo 0) {
            for (j in n - 1 downTo 0) {
                val cur = (num1[i] - '0') * (num2[j] - '0')
                array[i + j + 1] += cur
                if (array[i + j + 1] >= 10) {
                    //sum up carry and save in left of (i + j + 1)
                    array[i + j] += (array[i + j + 1]) / 10
                    //update current digit
                    array[i + j + 1] = (array[i + j + 1]) % 10
                }
            }
        }
        val result = StringBuilder()
        for (num in array) {
            if (!(result.isEmpty() && num == 0)) {
                result.append(num)
            }
        }
        return if (result.isEmpty()) "0" else result.toString()
    }
}
原文地址:https://www.cnblogs.com/johnnyzhao/p/14184134.html