-
设计一个算法,将一个十进制正整数转换为相应的二进制数。
例如:将十进制整数转换成二进制数通常采用除2取余数法。例如将十进制12转换为二进制数据1100的过程。
12 % 2 = 0,0进栈,12/2=6, 0
6%2 = 0, 0 进栈,6/2=3,0,0
3 % 2=1, 1进栈,3/2=1,0,0,1
1%2 =1, 1进栈,1/2=0,0,0,1,1 ------- 退栈并输出,转换结果 1100 -
代码:
#include<iostream>
#define maxsize 50
using namespace std;
typedef int elemtype;
typedef struct//定义栈
{
elemtype data[maxsize];
int top;
}sqstack;
int initstack(sqstack *&s)//初始化
{
s=(sqstack *)malloc(sizeof(sqstack));
s->top=-1;
return 0;
}
int destroystack(sqstack *&s)//销毁
{
free(s);
return 0;
}
bool stackempty(sqstack *s)//判断是否空
{
if(s->top==-1)
return true;
else return false;
}
bool push(sqstack *&s,elemtype e)//压栈
{
if(s->top==maxsize-1)
return false ;
s->top++;
s->data[s->top]=e;
return true;
}
int pop(sqstack *&s)//出栈
{
elemtype e;
if(s->top==-1)
{
cout<<"栈为空。";
return 0;
}
else
{
while(s->top!=-1)
{
e=s->data[s->top];
s->top--;
cout<<e;}
return 0;
}
}
int main()
{
sqstack *s;
elemtype e,p;
cout<<"请输入要转换的十进制(正整数)数字:"<<endl;
cin>>e;
initstack(s);
stackempty(s);
while(e>0)
{
p=e%2;
e=(e-p)/2;
push(s,p);
}
cout<<"转化为二进制为:"<<endl;
pop(s);
destroystack(s);
cin>>e;
return 0;
}