Roman Numeral to Integer
Problem
Roman digits have fixed values: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000. Adjacent symbols add — except when a smaller value precedes a larger one, in which case the smaller is subtracted (IV = 4, IX = 9, XL = 40, and so on). Walk the string left to right and add or subtract each digit's value based on what follows it.
Input
s = "MCMXLIV"Output
1944M (1000) + CM (900) + XL (40) + IV (4) = 1944.
def roman_to_int(s):
v = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
total = 0
for i, ch in enumerate(s):
cur = v[ch]
nxt = v[s[i + 1]] if i + 1 < len(s) else 0
total += -cur if cur < nxt else cur
return total
function romanToInt(s) {
const v = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
let total = 0;
for (let i = 0; i < s.length; i++) {
const cur = v[s[i]];
const next = i + 1 < s.length ? v[s[i + 1]] : 0;
total += (cur < next) ? -cur : cur;
}
return total;
}
class Solution {
public int romanToInt(String s) {
Map<Character, Integer> v = Map.of(
'I',1,'V',5,'X',10,'L',50,'C',100,'D',500,'M',1000);
int total = 0;
for (int i = 0; i < s.length(); i++) {
int cur = v.get(s.charAt(i));
int next = (i + 1 < s.length()) ? v.get(s.charAt(i + 1)) : 0;
total += (cur < next) ? -cur : cur;
}
return total;
}
}
int romanToInt(const string& s) {
unordered_map<char, int> v = {{'I',1},{'V',5},{'X',10},{'L',50},
{'C',100},{'D',500},{'M',1000}};
int total = 0;
for (int i = 0; i < (int)s.size(); i++) {
int cur = v[s[i]];
int nxt = (i + 1 < (int)s.size()) ? v[s[i + 1]] : 0;
total += (cur < nxt) ? -cur : cur;
}
return total;
}