diff --git a/13-roman-to-integer.cpp b/13-roman-to-integer.cpp new file mode 100644 index 0000000..0766a4d --- /dev/null +++ b/13-roman-to-integer.cpp @@ -0,0 +1,64 @@ +#include +#include + +typedef std::map RomanNumeral; + +class RomanToIntegerSolution { + + private: + RomanNumeral numTable; + + public: + int romanToInt(std::string s) { + + unsigned long roman(0); + std::string remainder; + remainder.resize(s.length()); + + unsigned long singleRomanNumerals[255]; + + singleRomanNumerals['I'] = 1; + singleRomanNumerals['V'] = 5; + singleRomanNumerals['X'] = 10; + singleRomanNumerals['L'] = 50; + singleRomanNumerals['C'] = 100; + singleRomanNumerals['D'] = 500; + singleRomanNumerals['M'] = 1000; + + numTable["IV"] = 4; + numTable["IX"] = 9; + numTable["XL"] = 40; + numTable["XC"] = 90; + numTable["CD"] = 400; + numTable["CM"] = 900; + + auto len(s.length()); + unsigned long j(0); + unsigned long i = 0; + + for ( ; i < len-1; i++ ) { + char str[3]; + str[0] = s[i]; + str[1] = s[i+1]; + str[2] = 0; + + auto it(numTable.find(str)); + if (it != numTable.end()) { + roman += it->second; + i++; + } else { + remainder[j++] = s[i]; + remainder[j] = 0; + } + } + if ( i < len ) { + remainder[j++] = s[i]; + remainder[j] = 0; + } + for (i = 0; (i < remainder.length()) && (remainder[i] != 0); i++) { + roman += singleRomanNumerals[remainder[i]]; + } + + return roman; + } +}; diff --git a/main.cpp b/main.cpp index 8e8d855..3a607cd 100644 --- a/main.cpp +++ b/main.cpp @@ -3,6 +3,7 @@ #include "1-two-sum.cpp" #include "2-add-two-numbers.cpp" #include "9-palindrome-number.cpp" +#include "13-roman-to-integer.cpp" int main() { TwoSumSolution twoSumSolution; @@ -56,5 +57,8 @@ int main() { PalindromeNumberSolution p; std::cout << "Is 1 palindrome? " << p.isPalindrome(1) << std::endl; + RomanToIntegerSolution r; + std::cout << "MCMXCIV = " << r.romanToInt("MCMXCIV") << std::endl; + return 0; }