| 13 | using namespace std; |
| 14 | |
| 15 | class Solution |
| 16 | { |
| 17 | public: |
| 18 | int romanToInt(string s) |
| 19 | { |
| 20 | // Step 1: Mapping Roman numerals to their integer values |
| 21 | unordered_map<char, int> roman = { |
| 22 | {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; |
| 23 | |
| 24 | int result = 0; // Variable to store the final integer value |
| 25 | |
| 26 | // Step 2: Iterate through each character in the string |
| 27 | for (int i = 0; i < s.size(); ++i) |
| 28 | { |
| 29 | int curr = roman[s[i]]; // Current numeral value |
| 30 | int next = (i + 1 < s.size()) ? roman[s[i + 1]] : 0; // Next numeral value (if any) |
| 31 | |
| 32 | // Step 3: Apply subtraction rule |
| 33 | // If the current numeral is smaller than the next one, subtract it. |
| 34 | // Otherwise, add it to the result. |
| 35 | if (curr < next) |
| 36 | { |
| 37 | result -= curr; |
| 38 | } |
| 39 | else |
| 40 | { |
| 41 | result += curr; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | // Step 4: Return the computed integer value |
| 46 | return result; |
| 47 | } |
| 48 | }; |
| 49 |
nothing calls this directly
no outgoing calls
no test coverage detected