01:十进制转化为二进制
总时间限制:
1000ms
内存限制:
65535kB
描述
进制之间的转换是很常见的操作
输入
一个正整数
输出
对应的二进制
样例输入
9
样例输出
1001
提示
可以用数组
可以用递归
可以用C++中的STL栈结构来轻松实现它。
来源
金华信奥熊老师
#include<iostream>
using namespace std;
const int MAX_SIZE = 100;
template <typename T>
class seqStack
{
public:
seqStack();
~seqStack();
bool push(T x);
T Pop();
T GetTop();
bool Empty();
private:
T data[MAX_SIZE];
int top;
};
void Conbersion(int a)
{
seqStack<int> seq;
int t, i, q;
while (a!=0)
{
t = a % 2;
a = a / 2;
i=seq.push(t);
if (i == 0)
{
break;
}
}
while (!seq.Empty())
{
cout << seq.Pop();
}
}
int main()
{
seqStack<int> seq;
int n;
cin >> n;
Conbersion(n);
return 0;
}
template<typename T>
seqStack<T>::seqStack()
{
top = -1;
}
template<typename T>
seqStack<T>::~seqStack()
{
}
template<typename T>
bool seqStack<T>::push(T x)
{
if (top == MAX_SIZE - 1)
{
throw "溢出";
return false;
}
top++;
data[top] = x;
return true;
}
template<typename T>
T seqStack<T>::Pop()
{
if (top == -1)
{
throw"溢出";
}
T x = data[top];
top--;
return x;
}
template<typename T>
T seqStack<T>::GetTop()
{
if (Empty())
{
throw "空栈";
}
return data[top];
}
template<typename T>
bool seqStack<T>::Empty()
{
if (top == -1)
{
return true;
}
else
{
return false;
}
}