【数据结构】利用栈实现进制转换

本文介绍了一种使用C++编程语言中的静态数组实现栈数据结构的方法,并利用该栈来完成十进制数到任意进制数的转换。通过定义结构体、初始化栈、压栈、弹栈和获取栈顶元素等操作,实现了高效稳定的进制转换功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h>
#include <iostream>
//#include <cstring>
//#pragma GCC optimize(2)
#include<time.h>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
#define maxn 1005
#define inf 1e18
#define eps 0.00001
typedef long long ll;
const ll mod = 1e9+7;
const double pi = acos(-1);

typedef struct
{
    int *base;
    int *top;
    int stacksize;
}SqStack;

int InitStack(SqStack &S)
{
    S.base = new int[maxn];
    if(!S.base)
        exit(0);
    S.top = S.base;
    S.stacksize = maxn;
    return 1;
}

int Push(SqStack &S,int e)
{
    if(S.top-S.base == S.stacksize)
        return 0;
    *S.top++=e;
    return 1;
}

int Pop(SqStack &S,int &e)
{
    if(S.top == S.base)
        return 0;

    e = *--S.top;
    return 1;
}

int GetTop(SqStack S)
{
    if(S.top != S.base)
        return *(S.top-1);
}

void conversion(int N,int k)
{
    SqStack S;
    InitStack(S);

    cout << "将" << N << "转为" << k << "进制后的结果为:" ;

    while(N)
    {
        Push(S,N%k);
        N=N/k;
    }

    while( S.top != S.base )
    {
        int e;
        Pop(S,e);
        cout << e;
    }
    cout << endl;

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);

    //freopen("D:\\test1.in","w",stdout);
    //srand((int)time(0));

    cout << "请输入将要转为K进制的数N以及K" << endl;

    int num,k;

    cin >> num >> k;

    conversion(num,k);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值