解题思路其实很简单,就是利用竖向除法,但是在几个细节碰到困难
- 因为是十进制以上的除法,所以每次要判断字母还是数字,字母要-'A'+10,数字要-'0'
- 结果字符串添加字符时也要考虑是否大于10,添加字母时采用append(1,x),添加数字直接to_string()
#include <algorithm>
using namespace std;
string converse(int m,int n,string str){
string res="";
int carry=0;
while(str!=""){
for(int i=0;i<str.length();i++){
int temp;
if(str[i]>='A'&&str[i]<='Z'){
temp = str[i]-'A'+10 + carry*m;
}
else{
temp = str[i]-'0' + carry*m;
}
if(temp/n>=10){
str[i] = temp/n -10 +'A';
}
else{
str[i] = temp/n + '0';
}
carry = temp%n;
}
if(carry>=10){
res.append(1,carry-10+'a');
}
else{
res+=to_string(carry);
}
carry=0;
while(str[0]=='0'){
str = str.substr(1,str.length());
}
}
reverse(res.begin(),res.end());
return res;
}
int main(){
int m,n;
string str;
cin>>m>>n>>str;
cout<<converse(m,n,str);
}

京公网安备 11010502036488号