题目:
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.
高精度乘法,就是通过像小学那样列数式相乘,将每一层得到的数式相加,并获得最终的结果。
例如333乘55
3 3 3
5 5
1 6 6 5
1 6 6 5
1 8 3 1 5
通过将每一层得到的数式存起来,再相加就可以得到最终的结果,空余的地方以0作为补充。
一种c++的代码实现如下:
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
string multiply(string num1, string num2) {
//若有一个数为0,则立即返回0
if(num1 == "0" || num2 == "0") return "0";
int n1 = num1.length();
int n2 = num2.length();
string *process = new string[n2];
//结果,和反向结果,为了表示方便,用反向结果进行运算,将反向结果反向已得到最终的结果
string result, invert_result;
//将num2当做被乘数,则num2有多少位就会得到多少个数式,将其分别保存下来,并做初始化
for(int i = 0; i < n2; i++) {
// 每个数式的长度的定义,由两个乘数的长度加1确定
for(int j = 0; j < n1+n2+1; j++) {
process[i] += '0';
}
}
//乘法运算
for(int i = 0; i < n2; i++) {
int k = i;
//进位
int carry = 0;
for(int j = n1-1; j >= 0; j--) {
//乘数
process[i][k++] = ( ( (num2[n2-1-i]-'0')*(num1[j] - '0') ) % 10 + carry ) % 10 + '0';
//获得进位
carry = ( (num2[n2-1-i]-'0')* (num1[j] - '0') ) / 10 + ( ( (num2[n2-1-i]-'0')*(num1[j] - '0') ) % 10 + carry )/10;
}
//最开头的进位
if(carry != 0) process[i][k] = carry+'0';
}
int min_num_length = process[n2-1].length();
/*
for(int i = 0; i < n2; i++) {
cout<<process[i]<<endl;
}
*/
//将所有得到的舒适相加,获得最终的结果
if(n2 != 1) {
for(int j = 0; j < n1+n2; j++) invert_result += '0';
int carry = 0;
int last_carry = 0;
for(int i = 0; i < min_num_length; i++) {
carry = 0;
for(int k = 0; k < n2-1; k++) {
if(k == 0) {
invert_result[i] = ( (process[k][i]-'0')+(process[k+1][i]-'0') )%10+'0';
carry += ( (process[k][i]-'0')+(process[k+1][i]-'0') ) / 10;
} else {
int old_num = (invert_result[i]-'0');
invert_result[i] = ( old_num+(process[k+1][i]-'0') )%10+'0';
carry += ( old_num+(process[k+1][i]-'0') ) / 10;
}
}
if(last_carry != 0) {
int old_num = (invert_result[i]-'0');
invert_result[i] = ( (invert_result[i]-'0') + last_carry ) % 10+'0';
carry += ( old_num+ last_carry ) / 10;
}
last_carry = carry;
//cout<<carry<<" "<<last_carry<<endl;
}
} else{
invert_result += process[0];
}
int start = invert_result.length()-1;
//反向,并将开头的零去掉
while(invert_result[start] == '0') {
start--;
}
for(int i = start; i >= 0; i--) {
result+= invert_result[i];
}
//cout<<result<<endl;
return result;
}
};