十进制到二进制的数制转换
1. 解题思路
手工法,就是用辗转相除取余数的方法,停止条件就是商为0
转换为计算机算法,就是让计算机去帮我们算除法,然后让**余数进栈**
2. 算法步骤
1. 初始化一个栈
2. 输入一个n
3. n不为0,则将n%2 入栈,同时更新n = n/2
4. 当n = 0时停止3
5. 如果栈非空,则逐个弹出栈顶元素
6. 当栈空时停止程序
3. 程序
#define MAXSIZE 100
#include <iostream>
using namespace std;
typedef struct SequentialStack{
int *stack_base;
int *stack_top;
}SuqentialStack;
bool Initialze_Stack(SequentialStack &stack1);
bool Push(SequentialStack &stack1, int new_element);
bool Pop(SequentialStack &stack1, int &top_element);
bool IsEmpty(SequentialStack stack1);
void Decimal_to_Binary(int number);
int main(){
int a = 23;
Decimal_to_Binary(a);
return 0;
}
bool Initialize_Stack(SequentialStack &stack1)
{
stack1.stack_base = new int[MAXSIZE];
if(!stack1.stack_base)
return false;
else
{
stack1.stack_top = stack1.stack_base;
return true;
}
}
bool Push(SequentialStack &stack1, int new_element)
{
if (stack1.stack_top - stack1.stack_base == MAXSIZE)
{
return false;
}
else
{
*stack1.stack_top = new_element;
stack1.stack_top ++ ;
return true;
}
}
bool Pop(SequentialStack &stack1, int &top_element)
{
if(!(stack1.stack_top == stack1.stack_base))
{
stack1.stack_top--;
top_element = *stack1.stack_top;
return true;
}
else
return false;
}
bool Is_Empty(SequentialStack stack1)
{
if(stack1.stack_top == stack1.stack_base)
return true;
else
return false;
}
void Decimal_to_Binary(int n)
{
SequentialStack stack1;
int top_element;
Initialize_Stack(stack1);
while(n != 0)
{
Push(stack1, n%2);
n = n/2;
}
while(!Is_Empty(stack1))
{
Pop(stack1, top_element);
cout<< top_element << "\t" ;
}
cout<<endl;
}