类似题目:http://poj.org/problem?id=1220
高精度进制转换原理:https://www.cnblogs.com/kuangbin/archive/2011/08/09/2132467.html
①利用整型数组存储
参考博客:https://www.cnblogs.com/bhlsheji/p/5104558.html
#include <cstdio>
#include <cstring>
#include <cctype>
using namespace std;
const int maxn = 600;//大数的最大位数
char str[maxn];//存储要转换的大数,以字符形式存储
//oldbase:原基数。newbase:新基数。len:大数的长度 pos:下标
int oldbase, newbase, len, pos;
//a[maxn]:储存大数的最小整型。注意a[0]没有使用;r[maxn]:储存余数,即所求数的每一位
int a[maxn],r[maxn];
//将字符转换成相应进制的整数
int getNum(char ch){
if(isdigit(ch)) return ch - '0';
else if(isupper(ch)) return ch - 'A' + 10;
else return ch - 'a' + 36;
}
//将相应进制整数转换成相应的字符
char getChar(int i){
if(i >= 0 && i <= 9) return i + '0';
if(i >= 10 && i <= 35) return i - 10 + 'A';
return i - 36 + 'A';
}
//调用函数将字符串转化成相应进制的整数。按位转化
void chToNum(){
len = strlen(str);//测量字符串的长度
//遍历每个字符,一一相应转换,注意没有使用a[0]
for(int i = 1; i <= len; i++){
a[i] = getNum(str[i - 1]);
}
}
void conversion()//转化函数
{
int i;
pos = 0;
for(i = 1; i <= len;){
int j, k = 0;
//对数的每一位除新基数求商求余
for(j = i; j <= len; j++){
k = k * oldbase + a[j];//计算除数
a[j] = k / newbase;//求商
k %= newbase;//求余
}
r[pos++] = k;//记录最后一个余数
for(j = 1; j <= len && !a[j]; j++);//去除前导0
i = j;
}
}
//输出函数
void print()
{
//逆序输出余数,即为结果
while(pos--){
printf("%c", getChar(r[pos]));
}
printf("\n");
}
int main(){
int n;
scanf("%d %d %s", &oldbase, &newbase, str);
chToNum();//字符串转换为整型
conversion();//转化
print();//函数调用输出结果
return 0;
}①利用字符串存储
参考博客:https://blog.nowcoder.net/n/c514fef730cf40dc946117c6def48c8b
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
int getNum(char ch){
if(isdigit(ch)) return ch - '0';
if(isupper(ch)) return ch - 'A' + 10;
return ch - 'a' + 36;
}
char getChar(int i){
if(i <= 9) return i + '0';
if(i >= 10 && i <= 35) return i - 10 + 'A';
return i - 36 + 'a';
}
string convert(int m, string a, int n){
string res;
while(a.size() != 0){
int rem = 0;
for(int i = 0; i < a.size(); i++){
int tmp = rem * m + getNum(a[i]);
a[i] = getChar(tmp / n);//求商
rem = tmp % n;//取余
}
res += getChar(rem);
int pos = 0;
while(a[pos] == '0'){
pos++;
}
a = a.substr(pos);
}
reverse(res.begin(), res.end());
return res;
}
int main(){
int m, n;
string a;
while(cin >> m >> n >> a){
cout << convert(m, a, n) << endl;
}
return 0;
}
京公网安备 11010502036488号