This is apparently a popular question. It seems OK, it’s very easy. I think I already knew the rule of subtraction. I suppose questions that prompt the learner to consider “doing the work” of writing out a map is nice.
Maybe there’s something to it with the loop being backwards. What if I did it forwards? Seems like it’d end up in the same place: the condition in the if
statement would be a bit different, that’s all.
MAP = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
class Solution:
def romanToInt(self, s: str) -> int:
val = 0
prevC = None
for c in reversed(s):
if prevC is not None and MAP[c] < MAP[prevC]:
val -= MAP[c]
else:
val += MAP[c]
prevC = c
return val