题解 | #又一版 A+B#
又一版 A+B
https://www.nowcoder.com/practice/9255c05d45b8406c9b588d7c57aa920b
#include <stdio.h> #include <math.h> #include <stdbool.h> #define MAXSIZE 50 typedef int ElemType; typedef struct { ElemType data[MAXSIZE]; int top; } Stack_int; // 初始化一个数字栈: void InitStack(Stack_int* S) { S->top = -1; } // 进栈: bool Push(Stack_int* S, ElemType x) { if (S->top == MAXSIZE - 1) return false; else { S->data[++S->top] = x; return true; } } // 出栈: bool Pop(Stack_int* S, ElemType* x) { if (S->top != -1) { *x = S->data[S->top--]; return true; } else return false; } // 计算字符串长度: int Length(char a[]) { int n = 0; for (int i = 0; a[i] != '\0'; i++) { n++; } return n; } // 字符串相加: void AddString(char a[], char b[]) { int lena = Length(a); int lenb = Length(b); int len; if (lena >= lenb) len = lena + 1; else len = lenb + 1; char c[50] = ""; int m = len; int n = len; int t = len; while (lena) a[--len] = a[--lena]; for (int i = 0; i < len - lena; i++) a[i] = '0'; while (lenb) b[--t] = b[--lenb]; for (int i = 0; i < t - lenb; i++) b[i] = '0'; int number = 0; while (m--) { if ((a[m] - '0') + (b[m] - '0') + number < 10) { c[m] = '0' + ((a[m] - '0') + (b[m] - '0') + number); number = 0; } else { c[m] = '0' + ((a[m] - '0') + (b[m] - '0') + number - 10); number = 1; } } for (int k = 0; k < n; k++) a[k] = c[k]; int count = 0; while (c[count] == '0') count++; int p = Length(a); int o = 0; for (o = 0; count < p; count++) a[o++] = a[count]; for (o = o; o < p; o++) a[o] = '\0'; } int DecimalToBinary(char a[], int x) { int len = Length(a); int number = 0; for (int j = 0; j < len; j++) { number = number * 10 + (a[j] - '0'); a[j] = '0' + number / x; number = number % x; } int count = 0; while (a[count] == '0') count++; int k = 0; for (k; count < len; count++) a[k++] = a[count]; while (k < len) a[k++] = '\0'; return number; } int main() { Stack_int S; InitStack(&S); char a[20] = ""; char b[20] = ""; int m; while ((scanf("%d%s%s", &m, a, b) != EOF)) { if (m == 0) break; else { if(a[0]=='0'&&b[0]=='0') printf("0"); else { AddString(a, b); while (a[0] != '\0') { int x = DecimalToBinary(a, m); Push(&S, x); } while (S.top != -1) { int x; Pop(&S, &x); printf("%d", x); } printf("\n"); } } } return 0; }