c 十进制转二进制

Problem Description
Give you a number on base ten,you should output it on base two.(0 < n < 1000)

Input
For each case there is a postive number n on base ten, end of file.

Output
For each case output a number on base two.

Sample Input
1
2
3

Sample Output
1
10
11

代码:

#include<stdio.h>
#include<string.h>
void main()
{
    int n,i,j,max;
	char a[50]={0};
    while(~scanf("%d",&n))
    {
		max = 0;//reset
		memset(a,0,sizeof a);
		for(i=0;i<n;i++){//模拟进位
		    a[0]++;
			for(j=0;j<50;j++){
				if(a[j]>=2){
				    a[j]-=2;
					a[j+1]++;
				}
			}
		}
		for(i=0;i<50;i++){//找到最大非零值下标
			if(a[i]>0){
			    max = i;
			}
		}
		for(i=max;i>=0;i--){//反向输出
		    printf("%d",a[i]);
		}
		printf("\n");
    }
}


猜你喜欢

转载自blog.csdn.net/qq_40811682/article/details/88352054