天天看點

杭電2051——Bitset(棧)題目:Bitset

題目: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

思路:

這道題是要實作十進制轉二進制。

下面是在網上找的十進制轉為二進制的示意圖

杭電2051——Bitset(棧)題目:Bitset

我們從示意圖中可以觀察到一個特點,那就是,最後的結果是從下向上寫的,也就是說,我們算出來的一串數,要從後往前輸出。

這個特點讓我想到了入棧和出棧,棧的特點是最先進棧的最後出棧,棧的這個特點剛好滿足這道題。

自從我想到了這個點以後,每次做進制的題都用這個方法,嘻嘻。對于我自己來說,我覺得用棧來解決進制轉換的問題是很簡便的。

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");
		
			
	}
}
           
上一篇: 2051Bitset

繼續閱讀