十进制到二进制的数制转换

十进制到二进制的数制转换

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值