Iterate through the string from left to right. If a character's value is smaller than the next character's value, subtract it; otherwise, add it to the total sum.
class Solution:
def romanToInt(self, s: str) -> int:
roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
res = 0
for i in range(len(s)):
if i + 1 < len(s) and roman[s[i]] < roman[s[i + 1]]:
res -= roman[s[i]]
else:
res += roman[s[i]]
return res
class Solution {
public int romanToInt(String s) {
Map roman = new HashMap<>();
roman.put('I', 1); roman.put('V', 5); roman.put('X', 10);
roman.put('L', 50); roman.put('C', 100); roman.put('D', 500); roman.put('M', 1000);
int res = 0;
for (int i = 0; i < s.length(); i++) {
if (i + 1 < s.length() && roman.get(s.charAt(i)) < roman.get(s.charAt(i + 1))) {
res -= roman.get(s.charAt(i));
} else {
res += roman.get(s.charAt(i));
}
}
return res;
}
}