任意长度两个正整数相加

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

#ifdef DEBUG
#define debug(fmt, args...) printf(fmt, ##args)
#else
#define debug(fmt, args...)
#endif

char *big_add(char *num1, char *num2)
{
	int c = 0; /* 开始最低进位为0 */
	int i = strlen(num1) - 1; /* 指向第一个加数的最低位 */
	int j = strlen(num2) - 1; /* 指向第二个加数的最低位 */
	int k;/* 指向结果的最低位 */
	
	debug("i = %d, j = %d\n", i, j);
	debug("num1 = %s, num2 = %s\n", num1, num2);

	/* 得到两个数中较大数的位数,并加1位作为预留进位空间 */
	int maxLength = strlen(num1) >= strlen(num2) ? strlen(num1) + 1 : strlen(num2) + 1;
	debug("maxLength = %d\n", maxLength);

	char *rst = (char *)malloc(sizeof(char) * (maxLength + 1));
	if (rst == NULL)
	{
		printf("malloc error\n");
		exit(1);
	}

	rst[maxLength] = '\0';
	k = maxLength - 1; /* 指向结果的最低位 */
	debug("k = %d\n", k);

	while ((i >= 0) && (j >= 0))
	{
		/* 进算本位的值 */
		rst[k] = ((num1[i] - '0') + (num2[j] - '0') + c)%10 + '0';
		/* 向高位进位的值 */
		c = ((num1[i] - '0') + (num2[j] - '0') + c) / 10;
		--i;
		--j;
		--k;
	}
	while (i >= 0)
	{
		rst[k] = ((num1[i] - '0') + c)%10 + '0';
		c = ((num1[i] - '0') + c) / 10;
		--i;
		--k;
	}
	while (j >= 0)
	{
		rst[k] = ((num2[j] - '0') + c)%10 + '0';
		c = ((num2[j] - '0') + c) / 10;
		--j;
		--k;
	}

	rst[0] = c + '0';

	/* 之所以返回首地址而不在该函数去判断是否有进最高位是因为要释放内存
 	 * 否则在没有进位的情况下内存释放会有问题 
 	 */	
	return rst;
/*
	if (rst[0] != '0')
	{
		debug("in if\n");
		return rst;
	}
	else
	{
		debug("in else if\n");
		return (rst + 1);
	}
*/
}

int main(int argc, char **argv)
{
	char *res = NULL;

	if (argc != 3)
	{
		printf("Usage:\n");
		printf("%s num1 num2\n", argv[0]);
		return -1;
	}

	res = big_add(argv[1], argv[2]);
	if (res[0] != '0')
		printf("%s + %s = %s\n", argv[1], argv[2], res);
	else
		printf("%s + %s = %s\n", argv[1], argv[2], res + 1);
		

	free(res);
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值