Multiply Strings
Total Accepted: 62981
Total Submissions: 265241
Difficulty: Medium
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note:
- The numbers can be arbitrarily large and are non-negative.
- Converting the input string to integer is NOT allowed.
- You should NOT use internal library such as BigInteger.
Subscribe to see which companies asked this question
Hide Similar Problems
思路:
如:num1="123",num2="45";对应结果存储在ans[num1.size()+num2.size()]中。
从右到左对位相乘,只要确定相乘后的结果在ans中位置即可。
参考讨论区的图:
即:num1[i] * num2[j]相乘后的对应位置为:i+j和i+j+1。
c++ code:
class Solution {
public:
string multiply(string num1, string num2) {
int len1 = num1.size(),len2 = num2.size();
string ans(len1+len2,'0');
for(int i=len1-1;i>=0;i--) {
for(int j=len2-1;j>=0;j--) {
int mul = (num1[i]-'0') * (num2[j]-'0');
int p1 = i + j;
int p2 = p1 + 1;
int sum = mul + ans[p2]-'0';
ans[p2] = sum % 10 + '0';
ans[p1] += sum / 10; // 这里ans[p1]-'0',而sum/10+'0',因此抵消
}
}
// 去掉前面的0
int start = 0;
while(ans[start]=='0') start++;
ans = ans.substr(start);
return ans.size()==0 ? "0" : ans;
}
};