Title Description
A length of up to 30 decimal digits nonnegative integer output is converted into a binary number.
Entry
A plurality of sets of data, each of the behavior of a length of not more than 30 decimal nonnegative integer.
(Note that the number is a decimal number 30 may have, instead of the integer 30bits)
Export
Binary number corresponding to each line of output.
Sample input
985
211
1126
Sample Output
1111011001
11010011
10001100110
#include <stdio.h>
#include <string.h>
int main()
{
char d[32];
int ans[100];
while(scanf("%s",d)!=EOF)
{
int sum=1,i=0,num[32],t,len=strlen(d);
for(int j=0; j<len; j++)
num[j]=d[j]-'0'; //将字符型数字转换为数字
while(sum)
{
sum=0; //用于进行循环,当所得的数剩1,除以2得0时结束
for(int j=0; j<len; j++)
{
t=num[j]/2;
sum+=t;
if(j==len-1) //如果是此数的最后一位,直接除二取余
ans[i++]=num[j]%2;
else
num[j+1]+=(num[j]%2)*10; //操作后得到的余数加上下一位数
num[j]=t; //得到商
}
}
for(int j=i-1; j>=0; j--) //逆向取余
printf("%d",ans[j]);
printf("\n");
}
return 0;
}
operation result:
Implementation process:
23 For example, an initial array of num 2 3, num becomes 11 after the for loop, ans [0] = 1; num becomes longer for later cycles 0 5, ans [1] = 1; num becomes longer for later cycles 0 2, ans [2] = 1; num becomes longer for later cycles 0 1, ans [3] = 0; num becomes longer for later cycles 0 0, ans [4] = 1. Finally, reverse output ans array.