這個題很坑,有幾種情況要測試
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;
}
測試正確