【Leetcode】43. Multiply Strings

Description

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# @param {String} num1
# @param {String} num2
# @return {String}
def multiply(num1, num2)
return "0" if num1 == "0" || num2 == "0"

size1 = num1.size
size2 = num2.size

rst = []

for i in 1..num1.size
for j in 1..num2.size
rst[i + j - 2] = rst[i + j - 2].to_i + num1[size1 - i].to_i * num2[size2 - j].to_i
end
end

for i in 0..(rst.size-1)
if rst[i] / 10 > 0
rst[i + 1] = rst[i + 1].to_i + rst[i] / 10
rst[i] = rst[i] % 10
end
end

rst.join.reverse
end