Give you a number on base ten,you should output it on base two.(0 < n < 1000)
Input
For each case there is a postive number n on base ten, end of file.
Output
For each case output a number on base two.
将十进制数转化成二进制数,思路很简单,我用的是C++中的栈,必须要清楚栈中元素是先进后出,即如果压栈顺序为1、2、3,那么出栈顺序为3、2、1。
首先看一下原c++栈的方法的基本用法:
- push(): 向栈内压入一个成员;
- pop(): 从栈顶弹出一个成员;
- empty(): 如果栈为空返回true,否则返回false;
- top(): 返回栈顶,但不删除成员;
- size(): 返回栈内元素的大小;
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int>q;
int n;
while(cin>>n)
{
while(n/2!=0)
{
q.push(n%2);
n=n/2;
}
cout<<n;
while(!q.empty())
{
cout<<q.top();
q.pop();
}
cout<<endl;
}
return 0;
}