【任务】
把一个x进制的数转换成一个y进制的数
模板:
string transform(int x,int y,string s) { string res=""; int sum=0; for(int i=0;i<s.length();++i) { if(s[i]=='-') continue; if(s[i]>='0'&&s[i]<='9') { sum=sum*x+s[i]-'0'; } else { sum=sum*x+s[i]-'A'+10; } } while(sum) { char tmp=sum%y; sum/=y; if(tmp<=9) { tmp+='0'; } else { tmp=tmp-10+'A'; } res=tmp+res; } if(res.length()==0) res="0"; if(s[0]=='-') res='-'+res; return res; }
题目:
链接:http://acm.hdu.edu.cn/showproblem.php?pid=2031
#include<iostream> #include<cstdio> #include<cstring> #include<string> using namespace std; string s; int r; string transform(int r,string s) { string res=""; int sum=0; for(int i=0;i<s.length();++i) { if(s[i]=='-') continue; if(s[i]>='0'&&s[i]<='9') { sum=sum*10+s[i]-'0'; } else { sum=sum*10+s[i]-'A'+10; } } while(sum) { char tmp=sum%r; sum/=r; if(tmp<=9) { tmp+='0'; } else { tmp=tmp-10+'A'; } res=tmp+res; } if(res.length()==0) res="0"; if(s[0]=='-') res='-'+res; return res; } int main() { while(cin>>s>>r) { string tt=transform(r,s); cout<<tt<<endl; } return 0; }