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
|
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
int main(int argc, char *argv[]) {
const string units[] = {"ZERO", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
const string tens[] = {"ZERO", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
const string hundreds[] = {"ZERO", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
const string thousands[] = {"ZERO", "M", "MM", "MMM"};
string input;
while (cin >> input) {
for (int i = 0; i < input.length(); ++i) { //Make input uppercase
input.at(i) = toupper(input.at(i));
}
int result = 0;
for (int j = (sizeof(thousands) / sizeof(thousands[0])); j > 0; --j) {
if ((input.rfind(thousands[j]) == 0)) { //if value of thousands index j is found at position 0 of input
result += (j * 1000);
input.erase(0, (thousands[j].length())); //Removes roman numerals from string
break;
}
}
for (int j = (sizeof(hundreds) / sizeof(hundreds[0])); j > 0; --j) {
if ((input.rfind(hundreds[j]) == 0)) {
result += (j * 100);
input.erase(0, (hundreds[j].length()));
break;
}
}
for (int j = (sizeof(tens) / sizeof(tens[0])); j > 0; --j) {
if ((input.rfind(tens[j]) == 0)) {
result += (j * 10);
input.erase(0, (tens[j].length()));
break;
}
}
for (int j = (sizeof(units) / sizeof(units[0])); j > 0; --j) {
if (input == units[j]) {
result += j;
input.erase(0, (units[j].length()));
break;
}
}
cout << result << '\n';
}
}
|