数据结构实验之栈与队列一:进制转换
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
有关栈与队列的详情讲解请点击链接:
https://blog.csdn.net/weixin_44143702/article/details/86620376
#include <iostream>
#include <stack>///C++中栈的操作函数
using namespace std;
///进制转换的详情去看百度百科
///https://baike.baidu.com/item/%E8%BF%9B%E5%88%B6%E8%BD%AC%E6%8D%A2/3117222?fr=aladdin#1
int main()
{
int n, r;
cin >> n >> r;
stack<int> s;///栈的创建
if(n == 0) cout << n << endl;///注意需要特判当 n = 1 时
else///转换进制后仍为 0
{
while(n > 0)
{
s.push(n % r);///使 n 对 r 取余
n /= r;/// n 除以 r
}
while(!s.empty())///此处等于 s.empty() != 1
{
///即 当函数返回值等于1的时候,栈为空
///此时非操作后为0,跳出循环
///若不为空,则返回值为0, 非 操作后为 1,继续循环
cout << s.top();///返回栈顶元素并输出
s.pop();///移除栈顶元素,不会返回栈顶元素的值
}
cout << endl;///输出换行
}
return 0;
}