直接从m进制转换成n进制,以防用例有大数所以用字符串处理。编写字符串除法和字符串求余实现。。。
#include <iostream> #include <cstdio> #include <stack> #include <string> #include <cstring> #include <vector> #include <algorithm> using namespace std; int getvalue(char c){ if(c>='0' && c<='9'){ return c-'0'; } else{ return c-'A'+10; } } char getcharacter(int n){ if(n<10) return '0'+n; else return 'A'+n-10; } char qiuyu(string s,int n,int m){//在字符串除法的基础上很容易得到求余函数 int yushu=0; int current; for(int i=0;i<s.size();i++){ current=yushu*m+getvalue(s[i]); s[i]=getcharacter(current/n); yushu=current%n; } if(yushu<10) return '0'+yushu; else return 'a'+yushu-10; } string divide(string s,int n,int m){//字符串除法 int yushu=0; int current; for(int i=0;i<s.size();i++){ current=yushu*m+getvalue(s[i]); s[i]=getcharacter(current/n); yushu=current%n; } while(s[0]=='0' && s.size()>1) s=s.substr(1,s.size()-1); return s; } int main(){ int m,n; string s; vector<char> nnum; while(cin>>m>>n){ cin>>s; while(s!="0"){ nnum.push_back(qiuyu(s,n,m)); s=divide(s,n,m); } for(int i=nnum.size()-1;i>=0;i--) cout<<nnum[i]; cout<<endl; nnum.clear(); } return 0; }