大数相乘算法:第一位与第一位相乘如果大于10,则对10取于,余数保留,再对除10,除数进位。循环对每一位进行相同的操作则最后的结果即为所求。
#include <string.h>
#include <map>
using std::map;
void InverseStr(char* str)
{
if(str == NULL)
return;
int leA = (int)strlen(str);
char ch;
for(int i = 0; i < len/2;i++)
{
ch = str[i];
str[i] = str[len - 1 - i];
str[lenA - 1 - i] = ch;
}
}
int multiply (const std::string strMultiplierA,const std::string strMultiplierB, std::string &strRst)
{
/* 在这里实现功能 */
char *strA = (char*)strMultiplierA.c_str();
char *strB = (char*)strMultiplierB.c_str();
if(strA == NULL || strB == NULL)
return -1;
int lenA = (int)strlen(strA);
int lenB = (int)strlen(strB);
if(lenA == 0 || lenB == 0)
return -1;
char *rst = (char*)malloc(lenA + lenB +1);
if(*strA == '0' || *strB == '0')
{
strRst = "0";
free(rst);
return 0;
}
InverseStr(strA);//strA进行倒置
InverseStr(strB);
map<int,int> m_mapA;
map<int,int> m_mapB;
map<int,int> m_mapC;
int cnt = 0;
while(*(strA) != '\0')//将strA放入map中
{
m_mapA[cnt++] = *strA - '0';
strA++;
}
cnt = 0;
while(*strB != '\0')
{
m_mapB[cnt++] = *strB - '0';
strB++;
}
cnt = 0;
map<int,int>::iterator iteA = m_mapA.begin();
map<int,int>::iterator iteB = m_mapB.begin();
for(;iteB != m_mapB.end();iteB++)//主程序大数相乘的处理,最后放入m_mapC中
{
for(iteA = m_mapA.begin();iteA != m_mapA.end();iteA++)
{
m_mapC[iteB->first + iteA->first] += (iteB->second * iteA->second)%10;
if(m_mapC[iteB->first + iteA->first] >= 10)
{
m_mapC[iteB->first + iteA->first + 1] += m_mapC[iteB->first + iteA->first]/10;
m_mapC[iteB->first + iteA->first] %= 10;
}
m_mapC[iteB->first + iteA->first + 1] += (iteB->second * iteA->second)/10;
if(m_mapC[iteB->first + iteA->first + 1] >= 10)
{
m_mapC[iteB->first + iteA->first + 2] += m_mapC[iteB->first + iteA->first + 1]/10;
m_mapC[iteB->first + iteA->first + 1] %= 10;
}
}
}
map<int,int>::iterator iteC = m_mapC.begin();
for(;iteC != m_mapC.end();iteC++)
{
rst[iteC->first] = iteC->second + '0';
cnt = iteC->first;
}
rst[++cnt] = '\0';
InverseStr(rst);
if(*rst == '0')
{
strRst = rst + 1;
free(rst);
return 0;
}
strRst = rst;
free(rst);
return 0;
}