C/C++编程题之大数相乘

大数相乘算法:第一位与第一位相乘如果大于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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值