题目描述
编写一个算法,将一个非负的十进制整数分别转换为一个二进制数、一个八进制数。
输入
【输入说明】
第一行输入需要转换的十进制元素,例如:666
输出
【输出说明】
第一行输出转换后的二进制元素,例如:1010011010
第二行输出转换后的八进制元素,例如:1232
样例输入 Copy
666
样例输出 Copy
1010011010 1232
【代码实现】
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define false 0;
typedef struct linestack{
int data;
struct linestack* next;
}linestack;
linestack* Push(linestack* stack, int a){
linestack *temp = (linestack*)malloc(sizeof(linestack));
temp->data=a;
temp->next=stack->next;
stack->next=temp;
return stack;
}
linestack* Pop(linestack* stack, int *x){
if(stack->next){
linestack *s=stack->next;
*x=s->data;
stack->next=s->next;
free(s);
}
else{
printf("栈为空!");
}
return stack;
}
int divideBy2(linestack *stack, int sample){
int i, result=0;
while(sample!=0){
i=sample%2;
Push(stack,i);
sample/=2;
}
while(stack->next){
stack=Pop(stack,&i);
result=result*10+i;
}
return result;
}
int divideBy8(linestack *stack, int sample){
int i,result=0;
while(sample!=0){
i = sample%8;
Push(stack,i);
sample/=8;
}
while(stack->next){
stack=Pop(stack,&i);
result=result*10+i;
}
return result;
}
int main(){
linestack *stack1 =(linestack*)malloc(sizeof(linestack));
stack1->next=NULL;
linestack *stack2 =(linestack*)malloc(sizeof(linestack));
stack2->next=NULL;
int res[100];
int i,test,j,res1,res2;
scanf("%d",&test);
res1 = divideBy2(stack1, test);
printf("%d\n",res1);
res2 = divideBy8(stack2, test);
printf("%d\n",res2);
return 0;
}