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

来源:互联网 发布:java图片文字识别 编辑:程序博客网 时间:2024/06/07 10:05

说明:

比如字符串"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);//动态申请空间别忘了释放,要遵循谁申请谁释放原则,这里我写的不好}