题目描述:
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.
一个数字的第i位乘一个数字的第j位,就会加在积的第(i+j)位上,所以先计算积的每一位的累计结果,然后再从最低位开始,发现大于9,就向高位进位。
class Solution {
public:
string multiply(string num1, string num2) {
int n1=num1.size();
int n2=num2.size();
vector<int> v(n1+n2,0);
int k=n1+n2-2; // i+j最多为n1+n2-2
for(int i=0;i<n1;i++)
for(int j=0;j<n2;j++)
v[k-i-j]+=(num1[i]-'0')*(num2[j]-'0');
int carry=0;
for(int i=0;i<n1+n2;i++)
{
v[i]+=carry;
carry=v[i]/10;
v[i]%=10;
}
string result;
int i=n1+n2-1;
while(v[i]==0) i--;
if(i<0) return "0";
while(i>=0)
{
result=result+to_string(v[i]);
i--;
}
return result;
}
};
本文介绍了一种不使用内置大数库或直接转换输入为整数的方法,实现两个大数字符串的乘法运算。通过逐位相乘并处理进位,最终返回乘积的字符串形式。适用于长度不超过110的数字字符串。
830

被折叠的 条评论
为什么被折叠?



