【面试题】纯数字字符串加法

说明:

比如字符串"123"和"1234"相加,返回"1357"

要点:

1.C语言中的atoi函数貌似是不能用了,比如字符串很长的话,会导致溢出(出题目的估计也不是让你用一些现成的函数)

2.考虑字符串不同长度的问题

3.考虑字符串前面有N个0的情况(比如:0123+0023)


//异常情况自己考虑,以下程序自己写的,有点长,希望能再简略一些,仅供参考

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strAdd(char* lhs,char* rhs)
{
	int lhsLength = strlen(lhs);
	int rhsLength = strlen(rhs);
	int carry = 0;
	int max = (lhsLength>rhsLength?lhsLength:rhsLength)+1;
	char* res = (char*)malloc(sizeof(char)*(max+1));
	memset(res,'0',sizeof(char)*(max+1));
	res[max]='\0';
	max--;
	lhsLength--;
	rhsLength--;
	while(lhsLength>=0&&rhsLength>=0)
	{
		if(lhs[lhsLength]+rhs[rhsLength]+carry-'0'<='9')
		{
			res[max--]=lhs[lhsLength--]+rhs[rhsLength--]+carry-'0';
			carry = 0;			
		}
		else
		{
			res[max--]=lhs[lhsLength--]+rhs[rhsLength--]+carry-'9'-1;
			carry = 1;			
		}
	}

	if(lhsLength<0&&rhsLength<0)
	{
		res[max]=carry+'0';
	}

	if(lhsLength>=0)
	{
		while(lhsLength>=0)
		{
			if(lhs[lhsLength]+carry<='9')
			{
				res[max--]=lhs[lhsLength--]+carry;
				carry = 0;				
			}
			else
			{
				res[max--]=lhs[lhsLength--]+carry-10;
				carry = 1;		
			}
		}
		res[max]=carry+'0';
	}

	if(rhsLength>=0)
	{
		while(rhsLength>=0)
		{
			if(rhs[rhsLength]+carry<='9')
			{
				res[max--]=rhs[rhsLength--]+carry;
				carry = 0;				
			}
			else
			{
				res[max--]=rhs[rhsLength--]+carry-10;
				carry = 1;		
			}
		}
		res[max]=carry+'0';
	}
	return res;
}

void main()
{
	char* s = strAdd("00999","1999");
	char *t;
	t = s;
	while(*t=='0')
		t++;
	printf("%s\n",t);
	free(s);//动态申请空间别忘了释放,要遵循谁申请谁释放原则,这里我写的不好
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值