// Convert a roman numeral into equivalent decimal number
// If the number is invalid numeral or out of range (1-50)
// return 0
#include <string>
#include <iostream>
#include <map>
class CRomanToDecimal {
std::map<std::string, int> romanStringToNumeralMapping;
public:
CRomanToDecimal() {
// http://codepad.org/loYoW8K1
const std::string units[] = {"", "I", "II", "III", "IV",
"V", "VI", "VII", "VIII", "IX"};
const std::string tens [] = {"", "X", "XX", "XXX", "XL", "L"};
for(int i = 1; i <= 50; ++i)
{
romanStringToNumeralMapping[ tens[i/10] + units[i%10] ] = i;
}
//#define INCLUDE_EXTENDED_LIST
#ifdef INCLUDE_EXTENDED_LIST
romanStringToNumeralMapping["IIII"] = 4; // Found on the dial pads of clocks
#endif
}
int toDecimal(std::string rn) {
// return romanStringToNumeralMapping[rn]; // If I return like this
// I should also give a function
// to clean invalid numerals (Murphy's law)
std::map<std::string, int>::iterator n = romanStringToNumeralMapping.find(rn);
const int number = ( n == romanStringToNumeralMapping.end() )
? 0
: n->second;
#define PRINT_DEBUG_LINES
#ifdef PRINT_DEBUG_LINES
std::cout << rn << ':' << ' ' << number << std::endl;
#endif
return number;
}
};
int main(int argc, char *const *argv) {
CRomanToDecimal roman;
if(argc > 1) {
for(int i = 1; i < argc; ++i) roman.toDecimal(argv[i]);
} else { // dummy run
std::cout << "Please input roman numerals to convert on command line"
<< endl;
roman.toDecimal("Mohit");
roman.toDecimal("IX");
roman.toDecimal("X");
roman.toDecimal("IXI");
roman.toDecimal("XL");
roman.toDecimal("IIII");
}
return 0;
}