将大数当做字符串进行处理,也就是将大数用十进制字符数组进行表示,然后模拟人们手工进行“竖式计算”的过程得到乘法的结果。
#include<iostream>
using namespace std;
#define MAXN 100
string multiply(char line1[], char line2[])
{
short number1[MAXN], number2[MAXN], result[MAXN];//number1,number2:两个乘数;result:乘积的结果
short len1 = strlen(line1);
short len2 = strlen(line2);
short len = len1 + len2;
bool line1isNegativeNumber = false;// 是否是负数
bool line2isNegativeNumber = false;// 是否是负数
for (int i = 0; i < len1; i++) {
char number = line1[i];
if (i == 0) {
if (number == '-' && len1 > 1) {
line1isNegativeNumber = true;
}
else if (number == '-' && len1 == 1){
string invalidString("Invalid input");
return invalidString;
}
else if (number > '9' || number < '0'){
string invalidString("Invalid input");
return invalidString;
}
}
else {
if (number > '9' || number < '0'){
string invalidString("Invalid input");
return invalidString;
}
}
if (number != '-') {
number1[len1 - i - 1] = number - '0';
}
}
for (int i = 0; i < len2; i++) {
char number = line2[i];
if (i == 0) {
if (number == '-' && len2 > 1) {
line2isNegativeNumber = true;
}
else if (number == '-' && len2 == 1){
string invalidString("Invalid input");
return invalidString;
}
else if (number > '9' || number < '0'){
string invalidString("Invalid input");
return invalidString;
}
}
else {
if (number > '9' || number < '0'){
string invalidString("Invalid input");
return invalidString;
}
}
if (number != '-') {
number2[len2 - i - 1] = number - '0';
}
}
if (line1isNegativeNumber) {
len1--;
}
if (line2isNegativeNumber) {
len2--;
}
memset(result, 0, sizeof(short) * (MAXN - 1));
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
result[i + j] = result[i + j] + number1[i] * number2[j];//逐位相乘
}
}
int carry = 0;
for (int i = 0; i <= len; i++){//进位
int k = result[i] + carry;
result[i] = k % 10;
carry = k / 10;
}
int realLen = 0;//实际的计算结果长度
for(int i = len - 1; i >= 0; i--) {
if (result[i] != 0) {//处理多余的零
realLen = i + 1;
break;
}
}
if (line1isNegativeNumber ^ line2isNegativeNumber) {
realLen++ ;
}
char *line = new char[realLen + 1];
if (realLen == 0) {
line[0] = 0 + '0';
line[1] = '\0';//字符串的结束标志
}
else {
int i = 0;
if (line1isNegativeNumber ^ line2isNegativeNumber) {
line[0] = '-';
i = 1;
}
for (; i < realLen; i++) {
line[i] = result[realLen - i - 1] + '0';
}
line[realLen] = '\n';
}
return line;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
char line1[MAXN], line2[MAXN];
while(cin >> line1 >>line2)
{
cout << multiply(line1, line2) << endl;
}
}
return 0;
}