1017: 进制转换问题
Description
利用栈类,实现将一个十进制整数转化为二至九进制之间的任一进制输出。函数原型void Convert(int num,int d),将十进制num转换为d进制,在函数体内实现输出即可。
若num为正整数,则算法规则如下:
循环(直至num为0)
{ 将num%d压栈;
num/=d;
}
循环(栈非空)
{
栈顶元素弹栈,输出(进制的高位)
}
要求程序能够处理正、负整数(含0)
Input
输入:6 2
输出:110
输入:90 8
输出:132
Output
Sample Input
6 2
Sample Output
110
//
// Created by Legends?Hu on 2020/2/4.
//
#include <iostream>
//#include "Stack.h"
using namespace std;
const int StackSize = 100;
template<class T>
class Stack {
private:
int top;
T data[StackSize];
public:
Stack();
void Push(T x);
T Pop();
T GetTop();
int Empty();
~Stack() {}
};
template<class T>
void Stack<T>::Push(T x) {
if (top == StackSize - 1) throw "Overflow";
data[++top] = x;
}
template<class T>
Stack<T>::Stack() {
top = -1;
}
template<class T>
T Stack<T>::Pop() {
if (Empty()) throw "Downflow";
return data[top--];
}
template<class T>
T Stack<T>::GetTop() {
return Empty() ? throw "Downflow" : data[top];
}
template<class T>
int Stack<T>::Empty() {
return top == -1;
}
void Convert(int num, int d) {
Stack<int> stack;
while (num) {
try {
stack.Push(num % d);
num /= d;
} catch (const char *msg) {
cout << "Stack is Full," << msg << endl;
}
}
while (!stack.Empty())
cout << stack.Pop();
cout << endl;
}
int main() {
int num, d;
cin >> num >> d;
Convert(num, d);
return 0;
}