0
点赞
收藏
分享

微信扫一扫

[leetcode] 43. Multiply Strings


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:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

分析

题目的意思是:求两个数字字符串的乘积。

  • 把错位相加后的结果保存到一个一维数组中,然后分别在每位上算进位,最后每个数字都变成一位,然后要做的是去除掉首位0,最后把每位上的数字按顺序保存到结果中即可

代码

class Solution {
public:
string multiply(string num1, string num2) {
string res="";
int m=num1.size();
int n=num2.size();
vector<int> v(m+n,0);
int k=m+n-2;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
v[k-i-j]+=(num1[i]-'0')*(num2[j]-'0');
}
}
int carry=0;
for(int i=0;i<m+n;i++){
v[i]+=carry;
carry=v[i]/10;
v[i]=v[i]%10;
}
int i=m+n-1;
while(v[i]==0){
i--;
}
if(i<0){
return "0";
}
while(i>=0) res.push_back(v[i--]+'0');
return res;
}
};

参考文献

​​[编程题]multiply-strings​​​​[LeetCode] Multiply Strings 字符串相乘​​


举报

相关推荐

0 条评论