[ create a new paste ] login | about

Link: http://codepad.org/2LG4SbjJ    [ raw code | output | fork ]

mohit_at_codepad - C++, pasted on Apr 11:
// 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;
}


Output:
1
2
3
4
5
6
7
Please input roman numerals to convert on command line
Mohit: 0
IX: 9
X: 10
IXI: 0
XL: 40
IIII: 0


Create a new paste based on this one


Comments: