两个数字字符串相乘

求两个字符串的乘积,结果存到字符串中,例如字符串一中存的“657891”,字符串二中存的“521”

输出342761211

#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<assert.h>

void mul(char *Input1, int n, char *Input2, int m,char *Output);
int main()
{
	int n, m;
	int i = 0;
	char Input1[100];
	char Input2[100];
	char *Output;
	char *Result;
	gets(Input1);
	gets(Input2);
	n = strlen(Input1);
	m = strlen(Input2);
	Output = (char *)malloc(sizeof(char) * (m+n+1));

	assert(n>0 && m > 0 && Output != NULL);

	mul(Input1, n, Input2, m,Output);
	Result = Output;
	while(*Result == '0' && Result < Output+(m+n-1))//如果结果是0,输出一个0
		Result++;
	printf("%s\n", Result);
        free(Output);
        return 0;
}

void mul(char *Input1, int n, char *Input2, int m,char *Output)
{
	int i = 0;
	int j = 0;
	char *endIn1 = Input1+n-1;
	char *endIn2 = Input2 + m-1;
	char *endOut = Output + m+n-1;
	char *ptemp;
	int overflow = 0;
	for(i = 0; i < n+m; ++i)
		Output[i] = '0';
	Output[i] = '\0';
	while(endIn2 >= Input2) //从乘数的最后一位开始依次与乘数相乘
	{
		ptemp = endOut;  
		while(endIn1 >= Input1)  
		{
			i = *endIn2 - '0';
			j = *endIn1 - '0';
			*ptemp += (i*j % 10 + overflow); //output原来的值 + 进位 + 这次乘的结果(可能大于10)
			overflow = i*j/10 + (*ptemp - '0')/10;//进位的值
			*ptemp = (*ptemp-'0')%10 + '0';  //output 的真实值
			ptemp--;  //依次计算output的每一位的值
			endIn1--; 
		}
		if(overflow != 0) //最后是不是还有进位
			*ptemp = overflow + '0';
		overflow = 0;
		endIn1 = Input1+n-1;
		endOut--;//每一轮循环相乘之后,与Output的最低位相加的时候也要左移一位
		endIn2--;
	}
	Output[m+n] = '\0';
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值