#include<iostream>
#include<string>
#include<cmath>
#include<stack>
using namespace std;
stack<char> NumChange(int from, int to, string num)
{
stack<char> result;
unsigned long long dec = 0ULL;
int j = 0;
bool largeC = false;
if (to < 2 || to > 36 || from < 2 || from > 36)
return result;
if (num[0] == '-')
j = 1;
for (int i = j; i < num.length(); ++i)
{
if (num[i] >= 'a')
dec += (10 + num[i] - 'a')*pow(from, num.length() - i - 1);
else if (num[i] >= 'A')
{
dec += (10 + num[i] - 'A')*pow(from, num.length() - i - 1);
largeC = true;
}
else
dec += (num[i] - '0')*pow(from, num.length() - i - 1);
}
if (j)
dec = ~(dec - 1);
while (dec)
{
int temp = dec%to;
if (temp >= 10)
{
if(largeC)
result.push(char(temp - 10 + 'A'));
else
result.push(char(temp - 10 + 'a'));
}
else
result.push(char(temp + '0'));
dec /= to;
}
return result;
}
int main(void)
{
stack<char>result;
int from, to;
string num;
while (true)
{
cin >> from >> to >> num;
result = NumChange(from, to, num);
while (!result.empty())
{
cout << result.top();
result.pop();
}
cout << endl;
}
return 0;
}
2-36进制数的任意转换
最新推荐文章于 2021-03-09 16:06:26 发布