十进制转二进制
//问题:将非负十进制整数转换为二进制数
//思想:除二取余,逆序输出
//每次%2,所得值入栈,除二再取余。
//注:因为C int型没有小数。故得数会向下取整。如5/2=2,3/2=1
#include "stdio.h"
#include "stdlib.h"
#define MAXSIZE 100
int BaseTrans(int n){
int i,result = 0;
int stack[MAXSIZE],top = -1;
while(n!=0){
i = n%2;
n = n/2;
printf("%d ",n);
stack[++top] = i;
}
while(top != -1){
i = stack[top];
--top;
result = result*10+i;
}
return result;
}
int main(){
int n=10;
printf("%d",BaseTrans(n));
getchar();
return 0;
}