I briefly looked at some other people's hints and see that the key to this problem is that: num1[i] * num2[j] will be at final result's [i+j] position and [i+j+1] for the carrier.
Given two non-negative integers
num1 and num2 represented as strings, return the product of num1 and num2.
Note:
- The length of both
num1andnum2is < 110. - Both
num1andnum2contains only digits0-9. - Both
num1andnum2does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ n1, n2 = len(num1), len(num2) res = [0 for _ in range(n1+n2+1)] num1 = num1[::-1] num2 = num2[::-1] for i in range(n1): b1 = int(num1[i]) for j in range(n2): b2 = int(num2[j]) cur_b = res[i+j] + b1 * b2 if cur_b <= 9: res[i+j] = cur_b else: res[i+j] = cur_b % 10 res[i+j+1] += cur_b / 10 res = map(str, res) res = ''.join(res[::-1]) i = 0 while i < len(res) - 1 and res[i] == '0': i += 1 return res[i:]
No comments:
Post a Comment