两个string相乘
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.
不要先将string转成int再进行计算,一个一个数字转成int再计算,就像小学刚开始学乘法一样。
123和456,两个三位数相乘,最长可能是6位。规律:一个n1位的数和一个n2位的数相乘,最大可能是n1+n2位数。用num[n1+n2]来存储结果。
位数 0 1 2 3 4 5 6
456*3 1 8
1 6
1 3
456*2 4 8
2 4
1 0
456*1 1 0
6
5
结果 5 6 0 8 8
C++版本。
string multiply1(string num1,string num2){
int len1 = num1.length();
int len2 = num2.length();
int bit = len1 + len2;
int num[200] ={0};
//if(len1==0 ||len2==0) return "0";//输入限制了不能是空
if(num1[0]=='0'||num2[0]=='0') return "0";
for(int i=len1-1;i>=0;i--){
for(int j=len2-1;j>=0;j--){
int tmp = (num1[i]-'0')*(num2[j]-'0');
tmp += num[i+j+1];//进位
num[i+j] += tmp/10;
num[i+j+1] = tmp%10;
}
}
int be=(num[0]==0)?1:0;
string s(bit-be,'0');
for(int i=0;i<bit-be;i++){
s[i] = char(num[i+be]+'0');
}
return s;
}