超长位数的字符数的加法与乘法

超长位数的字符数的加法:

测试用例:112233445566778899 + 998877665544332211 = 1111111111111111110

程序代码:

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAXLEN 100

void add(char * a,char * b,char * c)
{
    int i,j;
	int sa = strlen(a);
	int sb = strlen(b);
	int max = sa>sb ? sa : sb;
	int * s = (int *)malloc(sizeof(int) * (max + 1));//为保证运算和的不溢出,应是最长操作数的位数+1,范围是[0,max];
	int * A = (int *)malloc(sizeof(int) * max);
	int * B = (int *)malloc(sizeof(int) * max);

	for(i=0;i<max;i++)
		A[i] = B[i] = s[i] = 0;			//先初始化为0,防止高位相加时对应位不存在导致的问题
	s[max] = 0;

	for(i=0;i<sa;i++)				//将a倒置以便低位对齐相加
		A[i] = a[sa - i - 1] - '0';

	for(i=0;i<sb;i++)
		B[i] = b[sb - i - 1] - '0';

	for(i=0;i<max;i++)
		s[i] = A[i] + B[i];

	for(i=0;i<max;i++)				//集中处理进位问题
	{
		if(s[i]>=10)				// 若i = max-1时有进位,则s[max] != 0
		{
			s[i+1] += s[i] / 10;
			s[i] %= 10;
		}
	}

	if(s[max] != 0)					//最高位有进位数据范围为[0,max]
	{
		for(j=0;j<=max;j++)
		{
			c[j] = s[max - j] + '0';
		}
		c[max+1] = '\0';
	}
	else						//最高位无进位,数据范围为[0,max-1]
	{
		for(j=0;j<max;j++)
		{
			c[j] = s[max -1 - j] + '0';
		}
		c[max] = '\0';
	}

	free(A);
	free(B);
	free(s);
}


int main()
{
	char a[MAXLEN];
	char b[MAXLEN];
	char c[2 * MAXLEN];
	while(scanf("%s + %s",a,b) != EOF)
	{
		add(a,b,c);
		printf("%s + %s = ",a,b);
		puts(c);
	}
	return 0;
}

超长位数的字符数的乘法:

测试用例:112233445566778899 * 998877665544332211 = 112107482103740987777903741240815689

程序代码:

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAXLEN 100

void multiply(char * a,char * b,char * c)
{
    int i,j,ca,cb,* s;
    ca = strlen(a);	//a操作数的位数
    cb = strlen(b);	//b操作数的位数
    s = (int*)malloc(sizeof(int)*(ca+cb));	//s指向能够存储a和b的空间
    for (i=0;i<ca+cb;i++)
    	s[i] = 0;	//初始化s数组元素全为0
    for (i=0;i<ca;i++)
    	for (j=0;j<cb;j++)
    		s[i+j+1] += (a[i]-'0') * (b[j]-'0');

    for (i=ca+cb-1;i>=0;i--)
    	if (s[i]>=10)
    	{
    	    s[i-1] += s[i]/10;	//高位加上低位的进位
    	    s[i] %= 10;
        }
    i=0;
    while (s[i]==0)
    	i++;
   	for (j=0;i<ca+cb;i++,j++)
   		c[j] = s[i] + '0';
    c[j]='\0';
    free(s);
}


int main()
{
	char a[MAXLEN];
	char b[MAXLEN];
	char c[2 * MAXLEN];
	while(scanf("%s * %s",a,b) != EOF)
	{
		multiply(a,b,c);
		printf("%s * %s = ",a,b);
		puts(c);
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值