Description
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:
1 | Input: num1 = "2", num2 = "3" |
Example 2:
1 | Input: num1 = "123", num2 = "456" |
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.
Difficulty: Medium
Code:
1 | class Solution { |
题意
给定两个代表非负num1和num2的字符串,用字符串表示它们的乘积。字符串的长度小于110,只包含0-9。不能将输入转成int进行计算。
Solution 1
用一个数组pos保存m+n长度的数字,代表每一位上的数字,最后一个数字表示结果的个位。
从字符串num1和num2的右侧开始,提取对应位置上的数字并计算乘积,确定相乘后所影响的pos位置上的数字。
num1[i] * num2[j]将会影响pos[i+j]和pos[i+j+1]上的数字,对其进行更新。
最后遍历pos返回结果字符串。
1 | class Solution { |
时间复杂度: O()。
空间复杂度: O()。