北京大学---进制转换(大数运算)

题目描述
将一个长度最多为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;
}

猜你喜欢

转载自blog.csdn.net/rytyy/article/details/80504789