leetcode [43] Multiply Strings
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 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 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.
题目大意:
求解两个string字符数字相乘得到的结果
解法:
首先,两个长度为m和n的数字相乘,结果的长度一定不会超过m+n,要么是m+n,要么是m+n-1,要么是0。当num1和num2中有一个为0,那么结果就是0。
第一个数字上第i个数字和第二个数字的第j个数字相乘得到的结果会作用在结果的第i+j+1个数字上,然后前面的i+j个数字取决于进位。
C++:
class Solution {
public:
string multiply(string num1, string num2) {
if(num1=="0"||num2=="0") return "0";
int m=num1.size(),n=num2.size();
string res(m+n,'0');
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int t=int(num1[i]-'0')*int(num2[j]-'0');
int count=t/10;
res[i+j+1]=res[i+j+1]+t%10;
if(res[i+j+1]>'9'){
res[i+j+1]=(res[i+j+1]-'0')%10+'0';
count++;
}
int index=i+j;
while(index>=0&&count>0){
res[index]=res[index]+count;
if(res[index]>'9'){
res[index]=(res[index]-'0')%10+'0';
count=1;
}else{
count=0;
}
index--;
}
}
}
return res[0]=='0'?res.substr(1):res;
}
};

浙公网安备 33010602011771号