Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted.

Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted.
def roman(s):
    v = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    total = 0
    for i, c in enumerate(s):
        if i + 1 < len(s) and v[c] < v[s[i + 1]]: total -= v[c]
        else: total += v[c]
    return total
print(roman("MMXXIV"), roman("CDXLIX"), roman("XCIX"))
What is printed?
  1. A. 2026 449 99
  2. B. 2024 449 101
  3. C. 2024 451 99
  4. D. 2024 449 99

Correct answer: D. 2024 449 99

IV = 4, XL = 40, CD = 400, XC = 90, IX = 9 are the subtractive pairs. MMXXIV = 2000 + 20 + 4; CDXLIX = 400 + 40 + 9; XCIX = 90 + 9. Adding every symbol blindly gives 2026, 671 and 121. O(n).

More Coding Interview Problems questions

Exams that ask this topic