MCPcopy Create free account
hub / github.com/Hsinha11/Leetcode-solutions / Solution

Class Solution

13-Roman-to-Integer/roman-to-integer.cpp:15–48  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13using namespace std;
14
15class Solution
16{
17public:
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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected