Ordinary decimal to binary approach is to take the remainder divisor method.
0 digit decimal number, later found Now type long long int range of about 10 18 ^, 10 ^ 30 indicates insufficient. So the idea this problem is to use an array to store the value, and then use an array of ways modulo divisor simulation method:
① array The last number is the number of decimal mantissa, mantissa value of the modulo 2
The decimal representation of the array ② constantly divided by two.
Examples: b [] to store a decimal number, such as 13, so b [0-1] = {1,3}, num [] array to store the mantissa 2% value, i.e. the final binary storage reverse order
a.13, mantissa 3,3% 2 = 1, num [0] = 1;
b.12 tell me is 1,1 / 2 = 0, since the first is an odd number, an odd number not divisible by 2, the lower 3 + 10 = 13, so the low number by, (3 + 10) / 2 = 6,
Whereby B [] array into b [] = {0,6}, recycled ab, sequentially into an array of values:
{0,6} -> {0,3} -> {0, 1} -> { 0,0}, during num [] = {1,0,1,1}
So 13 = (1101) 2;
The code is given below:
#include <stdio.h>
#include <string.h>
int main()
{
char snum[32];
int b[32];
while(scanf("%s", snum) != EOF)
{
int i=0,len = strlen(snum);
//字符串转为整数,存到数组b[]中
for(i=0; i<len; i++)
b[i] = snum[i] -'0';
//对数组b[]模拟除商取余
i=0;
char num[200];
int k=0, cf, j,temp; //cf是进位
while(i<len)
{
num[k++] = (b[len-1] % 2) + '0'; //尾数取余,并存到二进制表示数组中
//对整个剩余的值除以2,从第i个位置到结束
cf=0; //每一轮cf都要清0
for(j=i; j<len; j++)
{
temp = b[j];
b[j] = (b[j] + cf)/2; //b[j]+cf进位10
if(temp % 2 == 1)
cf = 10;
else
cf = 0;
}
if(b[i] == 0) //高位如果变为0,处理下一个位置
i++;
}
//输出
for(j=k-1; j>=0;j--)
printf("%c",num[j]);
printf("\n");
}
return 0;
}