Written by
daweibayu
on
on
Poj 1220
#include <iostream>
#include <string>
using namespace std;
int charToNum(char element)
{
if(element <= '9')
return element - '0';
else if(element <= 'Z' && element >= 'A')
return element - 'A' + 10;
else if(element <= 'z' && element >= 'a')
return element - 'a' + 36;
}
char numToChar(int num)
{
if(num <= 9)
return num + '0';
else if(num <= 35 && num >= 10)
return num - 10 + 'A';
else if(num <=61 && num >= 36)
return num - 36 + 'a';
}
string divide(const string& sequence, int sourceBase, int targetBase, string& modeResult)
{
if(sequence.find_first_not_of('0') == string::npos)
return "";
string result;
int mode = 0;
for(int i = 0 ; i < sequence.length(); i++)
{
int value = charToNum(sequence[i]) + sourceBase * mode;
mode = value % targetBase;
value = value / targetBase;
result += numToChar(value);
}
modeResult = numToChar(mode) + modeResult;
divide(result, sourceBase, targetBase, modeResult);
return result;
}
string convertBase(const string& sequence, int sourceBase, int targetBase)
{
if(sequence == "0")
return "0";
string targetSequence;
divide(sequence, sourceBase, targetBase, targetSequence);
return targetSequence;
}
int main()
{
int n;
cin >> n;
int sourceBase, targetBase;
string sourceSequence, targetSequence;
while(n--)
{
cin >> sourceBase >> targetBase >> sourceSequence;
targetSequence = convertBase(sourceSequence, sourceBase, targetBase);
cout << sourceBase << " " << sourceSequence << endl;
cout << targetBase << " " << targetSequence << endl << endl;
}
}