杭電(hdu)2031 進制轉換

進制轉換

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 32185    Accepted Submission(s): 17867


Problem Description
輸入一個十進制數N,將它轉換成R進制數輸出。
 

Input
輸入數據包含多個測試實例,每個測試實例包含兩個整數N(32位整數)和R(2<=R<=16, R<>10)。
 

Output
爲每個測試實例輸出轉換後的數,每個輸出佔一行。如果R大於10,則對應的數字規則參考16進制(比如,10用A表示,等等)。
 

Sample Input
7 2 23 12 -4 3
 

Sample Output
111 1B -11
 
使用STL中的stack容器來存取餘數。若當餘數大於10的時候,要注意處理!!
代碼如下:
#include <iostream>
#include <stack>
#include <cmath>
using namespace std;

stack<int> s;

void gcd(int x,int y)
{
	int r=1;
	while(x)              //當除數等於零的時候,則跳出循環
	{
		r=x%y;
		s.push(r);
		x=x/y;
	}
}

int main()
{
	int N,R,flag;
	while(cin>>N>>R)
	{
		flag=0;
		if(N<0){N=abs(N);flag=1;}
		gcd(N,R);
		if(flag==1)cout<<"-";
		while(!s.empty())
		{
			if(s.top()==10)cout<<"A";
			else if(s.top()==11)cout<<"B";
			else if(s.top()==12)cout<<"C";
			else if(s.top()==13)cout<<"D";
			else if(s.top()==14)cout<<"E";
			else if(s.top()==15)cout<<"F";
			else cout<<s.top();
			s.pop();
		}
		cout<<endl;
	}
}


發佈了64 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章