棧應用於進制轉換

前面我們介紹了棧用於括號匹配,本次咱們介紹棧的其他應用。因爲棧先進後出的特點,剛好和進制轉換數據從後往前讀相吻合,所以棧也可以解決進制轉換的問題


#include<iostream>
using namespace std;
#include<assert.h>
#define ElemType int                    //定義數據元素的類型
#define STACK_SIZE 100                  //棧的大小

typedef struct stack                    //定義一個棧
{
    ElemType *base;
    size_t    capacity;
    int       top;
}stack;

void init_stack(stack *pst)             //初始化棧
{
    pst->base = (ElemType *)malloc(sizeof(ElemType) * STACK_SIZE);
    assert(pst->base != NULL);
    pst->capacity = STACK_SIZE;
    pst->top = 0;
}
void push(stack *pst, ElemType x)       //入棧
{
    if(pst->top >= pst->capacity)
    {
        cout<<"棧已滿,"<<x<<"不能入棧"<<endl;
        return;
    }
    pst->base[pst->top++] = x;
}
void pop(stack *pst)                    //出棧
{
    if(pst->top == 0)
    {
        cout<<"棧已空,不能出棧."<<endl;
        return;
    }
    pst->top--;
}
ElemType gettop(stack *pst)             //獲取棧頂元素
{
    assert(pst->top != 0);
    return pst->base[pst->top-1];
}
bool empty(stack *pst)                  //判斷棧是否爲空
{
    return pst->top == 0;
}
void Convert_2(int value)               //轉換爲二進制
{
    stack st;
    init_stack(&st);
    while(value)                        //若value不爲0,循環繼續,持續入棧
    {
        push(&st, value%2);
        value /= 2;
    }
    while(!empty(&st))                  //若棧不爲空,持續顯示棧頂元素並出棧
    {
        cout<<gettop(&st);
        pop(&st);
    }
    cout<<endl;
}

char* Convert_16(int value)            //轉換爲十六進制
{
    static char buffer[sizeof(int)*2+1]; //由sizeof(int)*8/4 得來+1用來存放'\0'
    for(int i=sizeof(int)*2-1; i>=0; --i)
    {
        buffer[i] = "0123456789ABCDEF"[value%16];   //建立一種映射關係
        value /= 16;
    }
    return buffer;                    //buffer前加有static因此可以作爲返回值傳遞
}

int main()
{
    int value;
    cout<<"input value:>";
    cin>>value;
    cout<<value<<":二進制=";
    Convert_2(value);
    cout<<value<<":十六進制=0x";
    cout<<Convert_16(value)<<endl;
}

咱們看一下程序運行的結果
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章