华为入职前测试:大数相乘

8 篇文章 0 订阅

这个题很坑,有几种情况要测试

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;
}

测试正确

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值