顺序栈的综合

题目描述

编写一个算法,将一个非负的十进制整数分别转换为一个二进制数、一个八进制数。 

输入

【输入说明】 

第一行输入需要转换的十进制元素,例如: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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值