杭电(hdu)2031 进制转换

来源:互联网 发布:云计算和数据中心 编辑:程序博客网 时间:2024/05/17 20:01

进制转换

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 223 12-4 3
 

Sample Output
1111B-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;}}


1 0
原创粉丝点击