题目描述
建立顺序栈或链栈,编写程序实现十进制数到二进制数的转换。
输入
输入只有一行,就是十进制整数。
输出
转换后的二进制数。
样例输入
10
样例输出
1010
参考程序
#include<iostream>
using namespace std;
#define maxsize 100
void concersion(int n){
int a[maxsize];
int top =0; //栈为空
while(n){
a[top++]=n%2; //入栈 ;先用后加
n=n/2;
}
while(top){
cout<<a[--top]; //先减后用
}
}
int main(){
int n;
cin>>n;
concersion(n);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 50
typedef struct stack
{
int data[Maxsize];
int top;
}Stack;
void Init(Stack *&S)
{
S=(Stack *)malloc(sizeof(Stack));
S->top=-1;
}
bool Push(Stack *&S, int elem)
{
if(S->top==Maxsize-1) return false;
S->top++;
S->data[S->top] = elem;
return true;
}
bool Pop(Stack *&S, int &elem)
{
if(S->top ==-1) return false;
elem=S->data[S->top];
S->top--;
return true;
}
int main()
{
int n;
scanf("%d", &n);
Stack *S;
Init(S);
while(n!=0)
{
int elem;
elem =n%2;
Push(S, elem);
n/=2;
}
while(S->top !=-1)
{
int elem;
Pop(S, elem);
printf("%d", elem);
}
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#define maxsize 100
typedef struct sqstack
{
int data[maxsize];
int top;
}sqtack;
void Initstack(sqstack *&s)
{
s=(sqstack *)malloc(sizeof(sqstack));
s->top=-1;
}
int push(sqstack *&s,int e)
{
if(s->top==maxsize-1)
return 0;
else
s->top++;
s->data[s->top]=e;
return 1;
}
int pop(sqstack *s,int &e)
{
if(s->top==-1)
return 0;
else
e=s->data[s->top];
s->top--;
return 1;
}
int main()
{
int n,e;
sqstack *s;
Initstack(s);
scanf("%d",&n);
while(n)
{
push(s,n%2);
n=n/2;
}
while(1)
{
int m=pop(s,e);
if(!m)
{
break;
}
printf("%d",e);
}
return 0;
}
程序仅供学习参考!
标签:return,961,sqstack,int,top,elem,SWUST,Stack,OJ From: https://blog.csdn.net/2301_77942204/article/details/136824691