大数乘法 - 大数作为字符串的C语言操作

【问题描述】

编写程序实现两个超长整数(大于等于0,每个最长80位数字)的乘法运算。

【输入形式】

从键盘分行读入两个超长整数,要考虑输入高位可能为0的情况(如00083),每行的最后都有回车换行。

【输出形式】

输出只有一行,是两个长整数的乘法运算结果,从高到低依次输出各位数字,各位数字紧密输出。除非结果为0,否则最高位不能为0

【输入样例】

134098703578230056
002340980000000000

【输出样例】

313922383102564996494880000000000

【样例说明】

进行两个整数乘法运算,134098703578230056 * 002340980000000000 = 313922383102564996494880000000000。

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

void reverse(char str[])
{
	int l=0,r=strlen(str)-1;
	char tmp;
	while (l < r)
	{
		tmp = str[l];
		str[l] = str[r];
		str[r] = tmp;
		l++, r--;
	}
}

void add(char A[],char B[], char rst[])
{
	reverse(A);
	reverse(B);
	int i = 0;
	int tmp, carryover = 0;
	while (A[i] != '\0'&&B[i] != '\0')
	{
		tmp = A[i] - '0' + B[i] - '0';
		if (tmp > 9)
		{
			tmp = tmp - 10;
			rst[i] = tmp + '0';
			if (carryover) rst[i]++;
			carryover = 1;
		}
		else
		{
			rst[i] = tmp + '0';
			if (carryover) rst[i]++;
			carryover = 0;
		}
		i++;
	}

	if (B[i] == '\0' && A[i] != '\0')
	{
		rst[i] = A[i];
		if (carryover) rst[i]++;
		i++;
		while (A[i] != '\0')
		{
			rst[i] = A[i];
			i++;
		}
	}
	else if (A[i] == '\0'&&B[i] != '\0')
	{
		rst[i] = B[i];
		if (carryover) rst[i]++;
		i++;
		while (B[i] != '\0')
		{
			rst[i] = B[i];
			i++;
		}
	}
	else if (A[i] == '\0'&&B[i] == '\0'&&carryover)
	{
		rst[i] = 1;
		i++;
	}

	while (rst[i-1] == '0'&&i>1) i--;
	rst[i] = '\0';
	reverse(A);
	reverse(B);
	if(A!=rst) reverse(rst);
}

void multiply(char A[], char B[], char rst[])
{
	int i,j,k,carryover;
	char intermed[161];
	rst[0] = '0';rst[1]='\0';
	int tmp;

	reverse(A);
	reverse(B);
	i = 0;
	carryover = 0;
	while (B[i] != '\0')
	{
		for (j = 0; j < strlen(A); j++)
		{
			tmp = (A[j] - '0')*(B[i] - '0');
			intermed[j] = '0' + tmp % 10;
			intermed[j] += carryover;
			carryover = 0;
			if (intermed[j] > '9') 
			{
				intermed[j] -= 10;
				carryover++;
			}
			while (tmp > 9)
			{
				tmp -= 10;
				carryover++;
			}
		}	
		if (carryover) intermed[j++] = '0' + carryover;
		carryover = 0;
		intermed[j] = '\0';
		reverse(intermed);
		for (k = 0; k < i; k++)	intermed[j+k] = '0';
		intermed[j+k] = '\0';

		add(rst, intermed, rst);
		i++;
	}
	reverse(A);
	reverse(B);
}

int main()
{
	char A[81],B[81];
	char rst[161];
	scanf("%s",A);
	scanf("%s",B);
	multiply(A, B, rst);
	printf("%s",rst);
	return 0;
}

    原文作者:大整数乘法问题
    原文地址: https://blog.csdn.net/jason_ranger/article/details/51250458
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞