/*
Description: 完美实现版(无冗余) 编写十进制一位加法器add() , 以被加位、加位、低位进位为参数,用十进制数字字符表示,以本位结果和高位进位为输出。 实现两个任意长整数加法,其他过程自理,不能使用字符串库函数。*/ #include<stdio.h> #include<stdlib.h> #include<memory.h> #include<ctype.h> #include<string.h>typedef struct{
char* str; int length; }String;typedef struct{
char c; char s; }Rs;String ReadStr()
{ String result; char *s = NULL; int count = 0; char ch = getchar(); ++count; while(ch != EOF && ch != ' ' && ch != '\n'){ s = (char *)realloc(s, sizeof(char)*count); s[count-1] = ch; ch = getchar(); ++count; } s = (char *)realloc(s, sizeof(char)*count); s[count-1] = '\0'; result.str = s; result.length = count - 1; //printf("s = %s, len = %d\n", s, count - 1); return result; }int max(int a, int b)
{ if(a > b) return a; else return b; }int ChtoI(char ch)
{ return ch - '0'; } char ItoCh(int x) { return x + '0'; } Rs add(char cx, char cy, char cz) { int x = ChtoI(cx); int y = ChtoI(cy); int z = ChtoI(cz); int sum = x + y + z; Rs r; r.c = ItoCh(sum%10); r.s = ItoCh(sum/10); return r; }void swap(char* c1, char *c2)
{ *c1 = (*c1)^(*c2); *c2 = (*c1)^(*c2); *c1 = (*c1)^(*c2); } char* reverse(char *s, int len) { int i = 0, j = len - 1; while(i < j){ swap(s+i, s+j); ++i, --j; } return s; } String AddStr(String str1, String str2) { String result;//返回值 int len = max(str1.length, str2.length); char *s = (char *)malloc( sizeof(char)*(len+1) ); char *s1 = str1.str, *s2 = str2.str; int i = str1.length - 1, j = str2.length - 1; int k = 0; Rs r; char sh = '0'; while(i >= 0 && j >= 0){ r = add(s1[i], s2[j], sh); s[k++] = r.c; sh = r.s; --i, --j; } while(i >= 0){ r = add(s1[i], '0', sh); s[k++] = r.c; sh = r.s; --i; } while(j >= 0){ r = add('0', s2[j], sh); s[k++] = r.c; sh = r.s; --j; } if(sh == '1'){ ++len; s = (char *)realloc( s, sizeof(char)*(len + 1) ); s[k++] = '1'; ///printf("k = %d, len = %d\n", k, len); } s[k++] = '\0'; result.str = reverse(s, len); result.length = len; return result; } int main() { String s1, s2; String sum; s1 = ReadStr(); while( s1.length > 0){ s2= ReadStr(); sum = AddStr(s1, s2); printf("%s\n", sum.str); free(s1.str); free(s2.str); free(sum.str); s1 = ReadStr(); } system("pause"); return 0; } 已在上AC!