UVA_355_The Bases Are Loaded

#include<iostream>    
#include<sstream>    
#include<string>    
#include<vector>    
#include<list>    
#include<set>    
#include<map>    
#include<stack>    
#include<queue>    
#include<algorithm>  
#include<bitset>
#pragma warning(disable:4996)    
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::set;
using std::multiset;
using std::map;
using std::multimap;
using std::stack;
using std::queue;
using std::priority_queue;
using std::bitset;
long long ToDecimal(const string &str, const long long &base)
{
	long long ret = 0;
	for (size_t i = 0; i < str.size(); i++)
	{
		ret *= base;
		switch (str[i])
		{
		case '0':ret += 0; break;
		case '1':ret += 1; break;
		case '2':ret += 2; break;
		case '3':ret += 3; break;
		case '4':ret += 4; break;
		case '5':ret += 5; break;
		case '6':ret += 6; break;
		case '7':ret += 7; break;
		case '8':ret += 8; break;
		case '9':ret += 9; break;
		case 'A':ret += 10; break;
		case 'B':ret += 11; break;
		case 'C':ret += 12; break;
		case 'D':ret += 13; break;
		case 'E':ret += 14; break;
		case 'F':ret += 15; break;
		default:break;
		}
	}
	return ret;
}
string ToQuery(long long decimal, const  long long &base)
{
	string str;
	while (decimal)
	{
		char character;
		if (decimal%base >= 0 && decimal%base <= 9)
		{
			character = decimal%base + '0';
		}
		else
		{
			character = decimal%base - 10 + 'A';
		}
		str = character + str;
		decimal /= base;
	}
	if (str.size())
	{
		//std::reverse(str.begin(), str.end());
		return str;
	}
	else
	{
		return "0";
	}
}
bool check(const string &str, const long long &base)
{
	for (size_t i = 0; i < str.size(); i++)
	{
		int digit;
		switch (str[i])
		{
		case '0':digit = 0; break;
		case '1':digit = 1; break;
		case '2':digit = 2; break;
		case '3':digit = 3; break;
		case '4':digit = 4; break;
		case '5':digit = 5; break;
		case '6':digit = 6; break;
		case '7':digit = 7; break;
		case '8':digit = 8; break;
		case '9':digit = 9; break;
		case 'A':digit = 10; break;
		case 'B':digit = 11; break;
		case 'C':digit = 12; break;
		case 'D':digit = 13; break;
		case 'E':digit = 14; break;
		case 'F':digit = 15; break;
		default:break;
		}
		if (digit >= base)
		{
			return false;
		}
	}
	return true;
}
int main()
{
	//freopen("input.txt", "r", stdin);    
	//freopen("output.txt", "w", stdout);
	string str1; long long base1, base2;
	while (cin >> base1 >> base2 >> str1)
	{
		if (!check(str1, base1))
		{
			cout << str1 << " is an illegal base " << base1 << " number" << endl;
			continue;
		}
		long long decimal = ToDecimal(str1, base1);
		string str2 = ToQuery(decimal, base2);
		cout << str1 << " base " << base1 << " = " << str2 << " base " << base2 << endl;
	}
	return 0;
}

你可能感兴趣的:(uva)