#include <iostream>
#include <string>
#include <iomanip>
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 sourceBase, targetBase;
string sourceSequence, targetSequence;
while(cin >> sourceSequence >> sourceBase >> targetBase)
{
targetSequence = convertBase(sourceSequence, sourceBase, targetBase);
if(targetSequence.length() > 7)
targetSequence = "ERROR";
cout << setw(7) <<targetSequence << endl;
}
}
poj 1546
最新推荐文章于 2018-10-09 10:20:14 发布