大整数加法

a: "15149697207"

b: "68021668610"

a、b两个字符串,求a、b的和。


思路:数字都是从低位开始相加,数组习惯从0下标开始取值,因此先把字符串进行翻转,再进行求和,最后将求和得到的结果翻转就是最后结果。


字符串翻转函数:

int reverse_str(char *str)
{
	int i,n;
	int len = 0;
	char *str_p = str;
	char tmp = 0;

	if (str == NULL) {
		return -1;
	}

	while (*str_p++) {
		len++;
	}

	if (len == 0) {
		return -1;
	}

	for (n = len - 1, i = len - n -1; n >= i; n--, i++ ) {
		tmp = str[n];
		str[n] = str[i];
		str[i] = tmp;
	}

	return 0;
}

求和函数:

int add_big_num(char *a, char *b, char *output)
{
	char *a_p = a;
	char *b_p = b;
	char *output_p = output;
	int tmp = 0;
	/*进位*/
	int plus = 0;
	/*每位加起来的总和,解决00+0=00的异常情况*/
	int total = 0;

	if ((a == NULL) || (b == NULL) || (output == NULL)) {
		return -1;
	}

	if (reverse_str(a)) {
		return -1;
	}

	if (reverse_str(b)) {
		return -1;
	}

	/*运算长度相同的那部分*/
	while ((*a_p != '\0') && (*b_p != '\0')) {
		tmp = (*a_p++ - '0') + (*b_p++ - '0') + plus;
		if (tmp > 9) {
			tmp %= 10;
			plus = 1;
		} else {
			plus = 0;
		}

		total += tmp;
		*output_p++ = '0' + tmp;
	}

	/*运算a字符串剩余的部分*/
	while (*a_p != '\0') {
		tmp = *a_p++ - '0' + plus;
		if (tmp > 9) {
			tmp %= 10;
			plus = 1;
		} else {
			plus = 0;
		}

		total += tmp;
		*output_p++ = '0' + tmp;
	}

	/*运算b字符串剩余的部分*/
	while (*b_p != '\0') {
		tmp = *b_p++  - '0' + plus;
		if (tmp > 9) {
			tmp %= 10;
			plus = 1;
		} else {
			plus = 0;
		}

		total += tmp;
		*output_p++ = '0' + tmp;
	}

	/*避免999+1得到000的情况*/
	if (plus) {
		*output_p++ = '1';
	}

	if (total == 0) {
		output[0] = '0';
		output[1] = '\0';
	}

	reverse_str(output);

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值