SDUT 2131 数据结构实验之栈与队列一:进制转换

 

 

数据结构实验之栈与队列一:进制转换

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

输入一个十进制非负整数,将其转换成对应的 R (2 <= R <= 9) 进制数,并输出。

Input

第一行输入需要转换的十进制非负整数;
第二行输入 R。

Output

输出转换所得的 R 进制数。

Sample Input

1279
8

Sample Output

2377

提示:本题属于栈操作,可以借助栈来完成,首先要明白其他进制转化为十进制的原理,从而反向推出由十进制转化为其他进制的方法,具体操作代码中会注释。

代码实现如下(g++):
#include <bits/stdc++.h>

using namespace std;

int main()
{
    stack<int>t;//C++中建栈方便,可以直接用stack代替
    int n,r,b;
    std::ios::sync_with_stdio(false);//防止使用cin超时
    cin>>n;
    cin>>r;
    if(n==0)
        cout<<"0";//0的话进制转化均为0,要注意
    while(n>0)
    {
        b=n/r;
        t.push(n%r);//将n对r取模入栈
        n=b;
    }
    while(!t.empty())
    {
        cout<<t.top();//将栈顶数据出栈
        t.pop();
    }
    return 0;
}


/***************************************************
Result: Accepted
Take time: 0ms
Take Memory: 208KB
****************************************************/

猜你喜欢

转载自www.cnblogs.com/jkxsz2333/p/9487739.html