# 13. Roman to Integer Difficulty: Easy ## Solution ```cpp= /** *** Author: R-CO *** E-mail: daniel1820kobe@gmail.com *** Date: 2020-11-09 **/ #define VERSION_0 0 #define VERSION_1 (VERSION_0 == 0) #if VERSION_0 #include <cstdlib> #include <string> using std::string; #include <unordered_map> using std::unordered_map; using RefMap = unordered_map<char, int>; class Solution { public: int romanToInt(string s) { int output = 0; int previous_value = 0; for (auto it = s.rbegin(); it != s.rend(); ++it) { int current_value = ref_map[*it]; if (current_value >= previous_value) { output += current_value; } else { output -= current_value; } previous_value = current_value; } return output; } private: RefMap ref_map{{{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}}; }; #elif VERSION_1 #include <string> using std::string; class Solution { public: Solution() { ref_map['I'] = 1; ref_map['V'] = 5; ref_map['X'] = 10; ref_map['L'] = 50; ref_map['C'] = 100; ref_map['D'] = 500; ref_map['M'] = 1000; } int romanToInt(string s) { int output = 0; int previous_value = 0; for (auto it = s.rbegin(); it != s.rend(); ++it) { int current_value = ref_map[*it]; if (current_value >= previous_value) { output += current_value; } else { output -= current_value; } previous_value = current_value; } return output; } private: int ref_map['Z'+1]; }; #endif #include <iostream> using std::cout; using std::endl; #include <vector> using std::vector; struct TestCaseStruct { string input; int expected_output; }; int main(int argc, char *argv[]) { vector<TestCaseStruct> test_cases = {{"III", 3}, {"IV", 4}, {"IX", 9}, {"LVIII", 58}, {"MCMXCIV", 1994}, {"XCIX", 99}}; Solution solution; size_t test_case_index = 0; for (auto &test_case : test_cases) { if (solution.romanToInt(test_case.input) == test_case.expected_output) { cout << "Test case [" << test_case_index << "] is pass." << endl; } else { cout << "Test case [" << test_case_index << "] is fail." << endl; } ++test_case_index; } return EXIT_SUCCESS; } ``` ## Result - VERISON_1 Success Details Runtime: 24ms, faster than 44.19% of C++ online submissions for Roman to Integer. Memory Usage: 6.2 MB, less than 5.20% of C++ online submissions for Roman to Integer. - VERSION_2 Success Details Runtime: 4 ms, faster than 94.23% of C++ online submissions for Roman to Integer. Memory Usage: 6.2 MB, less than 5.20% of C++ online submissions for Roman to Integer. ###### tags: `LeetCode-Easy` `C++`