题目:Bitset
Problem Description
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.
Sample Input
1
2
3
Sample Output
1
10
11
[题目链接]http://acm.hdu.edu.cn/showproblem.php?pid=2051
思路:
这道题是要实现十进制转二进制。
下面是在网上找的十进制转为二进制的示意图
我们从示意图中可以观察到一个特点,那就是,最后的结果是从下向上写的,也就是说,我们算出来的一串数,要从后往前输出。
这个特点让我想到了入栈和出栈,栈的特点是最先进栈的最后出栈,栈的这个特点刚好满足这道题。
自从我想到了这个点以后,每次做进制的题都用这个方法,嘻嘻。对于我自己来说,我觉得用栈来解决进制转换的问题是很简便的。
AC代码:
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int>binary;//定义一个栈
int n;
while(~scanf("%d",&n))
{
while(n>0)
{
binary.push(n%2);//入栈
n/=2;
}
while(!binary.empty())//判断栈是否为空
{
printf("%d",binary.top());//打印栈顶的数字
binary.pop();//出栈
}
printf("\n");
}
}