1. 程式人生 > >北京大學---進位制轉換(大數運算)

北京大學---進位制轉換(大數運算)

題目描述
將一個長度最多為30位數字的十進位制非負整數轉換為二進位制數輸出。
輸入描述:
多組資料,每行為一個長度不超過30位的十進位制非負整數。
(注意是10進位制數字的個數可能有30個,而非30bits的整數)
輸出描述:
每行輸出對應的二進位制數。
示例1
輸入
0
1
3
8
輸出
0
1
11
1000

#include<stdio.h>
#include<string.h>
#include <stdbool.h>

char numstr[100];
char res[100];
int main() {


    while
(scanf("%s",numstr)!=EOF) { int len = strlen(numstr); int j = 0; bool flag = true; while (flag) { int a = 0; for (int i = 0; i < len; i++) { if (i == len - 1) { res[j++] = (numstr[i] - '0'
) % 2 + '0'; } else numstr[i + 1] += (numstr[i] - '0') % 2 * 10 ; numstr[i] = (numstr[i] - '0') / 2+'0'; } for (int i = 0; i < len; i++) { if (numstr[i] == '0') a++; } if
(a==len) { flag = false; } } res[j] = '\0'; for (int i = 0, k = j - 1; i<k; i++, k--) { char temp = res[i]; res[i] = res[k]; res[k] = temp; } printf("%s\n", res); } return 0; }