这个题很坑,有几种情况要测试
1.如果有一个乘数为空,则返回-1
2,如果结果为0,返回的字符串不能为空,要为“0”;
#include "oj.h"
/*******************************************************
Prototype : multiply
Description : 两个任意长度的长整数相乘, 输出结果
Input Param :
const std::string strMultiplierA 乘数A
const std::string strMultiplierB 乘数B
Output :
std::string strRst 乘法结果
Return Value :
int 0 正确
-1 异常
********************************************************/
int multiply (const std::string strMultiplierA,const std::string strMultiplierB, std::string &strRst)
{
/* 在这里实现功能 */
string chengshua = strMultiplierA;
string chengshub = strMultiplierB;
int a = chengshua.length();
int b = chengshub.length();
int strRst_length = 0;
int c = (a+1)*(b+1);
int *p = new int[c];
int *pa = new int[a];
int *pb = new int[b];
if ((a == 0) || (b == 0))//测试是否有乘数为空
{
return -1;
}
for (int i = 0; i != c; i++)
{
p[i] = 0;
}
for (string::size_type index = 0; index != chengshua.length(); index++) //把乘数放到数组中
{
pa[a-1-index] = chengshua.at(index) - '0';
}
for (string::size_type index = 0; index != chengshub.length(); index++)
{
pb[b-1-index] = chengshub.at(index) - '0';
}
for (int temp_b = 0; temp_b != b; temp_b++) //每个位循环相乘
{
for (int temp_a = 0; temp_a != a; temp_a++)
{
p[temp_a+temp_b] += pa[temp_a]*pb[temp_b];
for (int x = temp_a + temp_b; x != c ; x++)
{
if (p[x]/10 == 0)
{
break;
}
else
{
p[x+1] = p[x+1] + p[x]/10;
p[x] = p[x]%10;
}
}
}
}
while (c-- > 0) //判断结果有几位
{
if (p[c] != 0)
{
strRst_length = c + 1;
break;
}
}
char ch;
for (int i = strRst_length - 1; i >= 0 ; i--) //把结果放入字符串中
{
ch = p[i] + '0';
strRst.push_back(ch);
}
if (strRst.empty())//如果结果为0,则输出字符串为“0”
{
strRst = "0";
}
return 0;
}
测试正确