自己现场写运算符重载太容易出错了,以后一定要记得背一套固定的Bigint的重载函数
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
#include <functional>
#include <cmath>
using namespace std;
class Bigint{
public:
string num;
Bigint(int x){
if(!x){
num.push_back('0');
}else{
while(x){
num.push_back(x%10+'0');
x/=10;
}
}
}
//需要重载4个:+=,*=,/=,%
void operator+=(int x){
string xtmp;
string ans;
if(x == 0){
xtmp.push_back('0');
}else{
while(x){
xtmp.push_back(x%10+'0');
x /= 10;
}
}
reverse(num.begin(),num.end());
if(num.size() > xtmp.size()){
xtmp.append(num.size()-xtmp.size(), '0');
}else if(num.size() < xtmp.size()){
num.append(xtmp.size()-num.size(), '0');
}
int last = 0;
for(int i=0; i<num.size(); i++){
int tmp = num[i]-'0'+xtmp[i]-'0'+last;
last = tmp/10;
ans.push_back(tmp%10+'0');
}
if(last){
ans.push_back(last);
}
reverse(ans.begin(),ans.end());
num = ans;
}
void operator*=(int x){
string ans;
reverse(num.begin(),num.end());
int last = 0;
for(int i=0; i<num.size(); i++){
int tmp = (num[i]-'0')*x + last;
last = tmp/10;
ans.push_back(tmp%10+'0');
}
while(last){
ans.push_back(last%10 + '0');
last /= 10;
}
reverse(ans.begin(),ans.end());
num.clear();
num = ans;
}
void operator/=(int x){
string ans;
int last = 0;
for(int i=0; i<num.size(); i++){
last *= 10;
int tmp = num[i]-'0'+last;
if(tmp>=x || (tmp<x&&!ans.empty()) || (tmp<x&&i==num.size()-1)){
ans.push_back(tmp/x + '0');
}
last = tmp%x;
}
num.clear();
num = ans;
}
int operator%(int x) const { //由除法修改,输出余数即可
int last = 0;
for(int i=0; i<num.size(); i++){
last *= 10;
last = (num[i]-'0'+last)%x;
}
return last;
}
};
int Char2Int(char ch){
if(ch>='0' && ch<='9'){
return ch-'0';
}else if(ch>='A' && ch<='Z'){
return ch-'A'+10;
}else{
printf("Error.\n");
exit(0);
return 0;
}
}
char Int2Char(int x){
if(x>=0 && x<=9){
return x+'0';
}else if(x>=10 && x<=35){
return x-10+'A';
}else{
printf("Error.\n");
exit(0);
return ' ';
}
}
string ConvertM2N(const string &x, int m, int n){//大于十进制的情况:需要实现字符与数字转换
string xn;
Bigint xt = 0;
//以m进制的读法读x,转换为n进制输出 不考虑非法输入
//先把x转为十进制
for(int i=0; i<x.size(); i++){//是这里xt会产生越界
xt *= m;
xt += Char2Int(x[i]);
}
if(xt.num == "0"){
xn.push_back('0');
}else{
while(xt.num != "0"){
xn.push_back(Int2Char(xt%n));
xt /= n;
}
}
reverse(xn.begin(),xn.end());
return xn;
}
int main(){
int m, n;
string x;
while(scanf("%d%d",&m,&n) != EOF){
getchar();
getline(cin, x);
printf("%s\n",ConvertM2N(x,m,n).c_str());
x.clear();
}
return 0;
}