LeetCode刷题笔记--43. Multiply Strings
43. Multiply Strings
Medium
911408FavoriteShare
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.
参考了网上大神的贴做的:https://blog.****.net/temptercyn/article/details/83079052
大神贴里没有代码解释,这样其实理解上还有有点问题。我把详细的解释写到我的代码中了:
特别要注意vector<int> 初始化的写法:vector<int> temp(个数,初始值),还要注意高位低位
class Solution {
public:
string multiply(string num1, string num2) {
if(num1=="0"||num2=="0")return "0";
string ans="";
int l1=num1.size();
int l2=num2.size();
vector<int> temp((l1+l2),0);//vector temp是用来存储每一位上的加和,比如3位数*3位数,最大的可能是3+3=6位数,因此temp[x],x的数量是l1+l2。这一句的意思是temp[10],每个temp里的int值为0。
int k=l1+l2-1;//这里为什么要-1,原因是后面会从0位开始,比如3位数乘3位数,最大6位数,那么,在数组中的表示是temp[5]。而为什么上面一句中不-1?因为C++规定在定义数组时,需要写数组中元素的个数,因此定义时不-1,表示时-1。
int carry=0;
//下面开始一位一位地取出num1和num2中的数字相乘
for(int i=0;i<l1;i++)
{
for(int j=0;j<l2;j++)
{
temp[k-i-j]+=(num1[l1-i-1]-'0')*(num2[l2-j-1]-'0');
//这句话可能比较难理解,其实结果中的每个位上都可能有不止1个数相加。我们从string的最高位开始逐个取出数字,temp[最高位]中存储的是最低位的数字
}
}
//上面数字逐个取出相乘已经做完了,下面计算carry(进位),并在temp中去掉进位
for(int i=0;i<(l1+l2);i++)
{
temp[k-i]+=carry;//先加上上一位的进位
carry=temp[k-i]/10;//计算下一次的进位
temp[k-i]=temp[k-i]%10;//留下个位上的值
}
//对temp的计算已经完成,下面转成string,temp[k]是最低位,我们需要从最高位(temp[0])开始转
int p=0;
while(temp[p]==0)p++;//如果高位是0,则往低位走
for(;p<=k;p++)
{
ans+=(temp[p]+'0');
}
return ans;
}
};