【LeetCode】43. Multiply Strings(C++)
阿新 • • 發佈:2018-12-02
地址:https://leetcode.com/problems/multiply-strings/
題目:
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
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
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.
理解:
應該是一道很經典的題了,有個大概思路,因為涉及到進位,肯定要從後往前來算,但是具體的還是很難自己實現。。還是看看別人的程式碼學習好啦!
實現:
來源:Brief C++ solution using only strings and without reversal
這種實現簡直不能更巧妙。
總結一下里面的點:
- 首先是結果字串的長度,可以這樣考慮。用
num1
的每一位去乘num2
,得到一個數。然後用前一位乘num2
,得到另一個,但是需要把第二個數乘10和第一個數相加。 - 用一位數乘
num2
,得到的結果的長度最多就是num2
的長度加一,因為一位數肯定小於10,而乘十的長度才加一。設num1
m
,num2
為n
,這樣每一位的結果長度最多為 。其中首位放的就是進位。
- 當
m==1
時,長為 ,m==2
,為 ,所以結果串長度最多為 。 - 對於
num1[i]
,num2[j]
,相乘結果在res[i+j+1]
。(考慮num1[m-1]
*num2[n-1]
,結果的最後一位為res[m+n-1]
)。 num1[i]
乘完num2
後,最後可能還有進位,這個進位應該是放在結果(n+1位數)的第一位,也就是sum[i](同樣考慮i=m-1,結果應該放在n+1位,res最後一位是m+n-1,從m-1到m+n-1是n+1位)
class Solution {
public:
string multiply(string num1, string num2) {
string res(num1.size() + num2.size(), '0');
for (int i = num1.size() - 1; i >= 0; --i) {
int carry = 0;
for (int j = num2.size() - 1; j >= 0; --j) {
int tmp = (res[i + j + 1] - '0') + (num2[j] - '0')*(num1[i] - '0') + carry;
res[i + j + 1] = tmp % 10 + '0';
carry = tmp / 10;
}
res[i] += carry;
}
auto pos = res.find_first_not_of('0');
if (pos == string::npos)
return "0";
return res.substr(pos, res.length() - pos);
}
};