Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly
问题就是给你两个数,这两个数都是用string存的,然后输出他们的结果,结果也是string。
但是结果太大了,一般的int肯定是不好使了。
我们先考虑一下123*123的情况
3*123结果 放在后3位
2*123结果 放在倒数第2位到第4位
1*123结果 放在倒数第3位到第5位
首先我们要明白一个n位的数 乘以 一个m位的数,两数的结果不会超过n+m位(想想999*999<999*1000=999000)
所以我们先申请一块m+n大小的字符串res作为结果,然后给他每一位都赋值为'0'(0+48)
然后往里添数即可
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") return "0";
int n1 = num1.size(), n2 = num2.size();
string res(n1 + n2, '0');
int jw = 0;
//n1*n2
for (int i = n1-1; i >= 0 ; i--)
{
for (int j = n2-1; j >= 0; j--)
{
int now = res[i + j + 1] - '0' + (num1[i] - '0')*(num2[j] - '0') + jw;
jw = now / 10;
res[i + j + 1] = now % 10 + '0';
}
res[i] += jw;
jw = 0;
}
while (res[0] == '0') res = res.substr(1);
return res;
}
};