43. Multiply Strings
题目
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
大意
答案
1 | class Solution { |
思路
简单来说,
假设两个整数的长度分别为了l1和l2,则其最后结果长度为l1+l2(最后有进位)或者l1+l2-1(最后没有有进位)。
因此,可以先用长度为l1+l2的数组记录结果,最后再转成字符串。
进行乘法的时候,先把各个位的相乘结果对应累加起来,即第1个整数的第i位(低位到高位)和第2个整数的第j位(低位到高位)相乘的结果应该存放在数组的i+j位。
其次,首先不管进位,直接把得到的值存在相应的位置上,就像
然后再一次性处理进位.
接着把前面多余的零去掉,然后加到字符串中即可.
Author: corn1ng
Link: https://corn1ng.github.io/2017/12/18/算法/leetcode43/
License: 知识共享署名-非商业性使用 4.0 国际许可协议