【面試題】純數字字符串加法

說明:

比如字符串"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);//動態申請空間別忘了釋放,要遵循誰申請誰釋放原則,這裏我寫的不好
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章