1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector< vector<string> > ROMAN = {
{"","I","II","III","IV","V","VI","VII","VIII","IX"},
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"","M","MM","MMM"} };
//=====================================================================
string noBlanks( string s )
{
string result;
for ( char c : s ) if ( c != ' ' ) result += c;
return result;
}
//=====================================================================
string intToRoman( int n )
{
if ( n <= 0 || n >= 4000 ) return "";
string s;
for ( int decade = 3, power = 1000; decade >= 0; decade--, power /= 10 )
{
n %= ( 10 * power );
s += ROMAN[decade][n/power];
}
return s;
}
//=====================================================================
int romanToInt( string s )
{
s = noBlanks( s );
int n = 0;
for ( int decade = 3, power = 1000; decade >= 0; decade--, power /= 10 )
{
for ( int j = ROMAN[decade].size()-1; j > 0; j-- )
{
string test = ROMAN[decade][j];
int size = test.size();
if ( s.size() >= size && s.substr( 0, size ) == test )
{
n += j * power;
s.erase( 0, size );
break;
}
}
}
if ( s != "" ) n = -1; // ill-defined string
return n;
}
//=====================================================================
int main()
{
int n;
string roman;
cout << "Input a number (1-3999): "; cin >> n;
roman = intToRoman( n );
if ( roman == "" ) cout << "Unable to convert\n";
else cout << roman << '\n';
cout << "\n\n";
cout << "Input a roman numeral: "; cin >> roman;
n = romanToInt( roman );
if ( n <= 0 ) cout << "Unable to convert\n";
else cout << n << '\n';
}
|