题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/0337e32b1e5543a19fa380e36d9343d7
#include <stdio.h> #include<stdbool.h> #define MAXSIZE 500 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; } // 长数字除法: int DecimalToBinary(char a[]) { int len = Length(a); int number = 0; for (int j = 0; j < len; j++) { number = number * 10 + (a[j] - '0'); a[j] = '0' + number / 2; number = number % 2; } 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() { char a[200] = " "; while ((scanf("%s", a)) != EOF) { Stack_int S; InitStack(&S); int x = 0; while (a[0] != '\0') { x = DecimalToBinary(a); Push(&S, x); } while (S.top != -1) { int y; Pop(&S, &y); printf("%d", y); } printf("\n"); } return 0; }