您的位置:首页 > 其它

43. Multiply Strings

2017-02-09 14:55 218 查看
Given two non-negative integers
num1
and
num2
represented as strings, return the product of
num1
and
num2
.

Note:

The length of both
num1
and
num2
is < 110.
Both
num1
and
num2
contains only digits
0-9
.
Both
num1
and
num2
does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

Subscribe to see which companies asked this question.

来源: https://leetcode.com/problems/multiply-strings/

分析

与大数相加类似下面的算法是按照正常的算数过程,计算出num1和num2每个位数字的乘积,然后再相加28ms
进一步改进因为add函数每一次都要reverse两个string,最后算数结束还需要再次reverse结果,导致效率很低
其实可以将乘法和最后相加的过程整合在一起。这里用到一个条件,两个数(一个n位,一个m位)相乘,则乘积最大长度,不超过n+m位这样的话,建立一个n+m位的string,作为存储乘积结果的字符串result,每次每个数字相乘后,就和result相加
num1: "11223" n = 5num2: "123456" m = 6index: 0 1 2 3 4 5 6 7 8 9 10result: 0 0 0 0 0 0 0 0 0 0 0 当 i = 2; j = 3时,指向的result位置是i+j+1 *
null
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: