InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Roman to Integer

easy Original ↗ 00:00

Problem

Roman numerals use seven symbols with fixed values: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. Numbers are written by placing symbols from largest to smallest and adding their values — except for six subtractive cases where a smaller symbol precedes a larger one and is subtracted: IV=4, IX=9, XL=40, XC=90, CD=400, CM=900. Given a valid Roman numeral string, return its integer value.

Examples

  • "III"3 — 1 + 1 + 1.
  • "LVIII"58 — 50 + 5 + 1 + 1 + 1.
  • "MCMXCIV"1994 — M(1000) + CM(900) + XC(90) + IV(4).

Constraints

  • 1 <= len(s) <= 15
  • s is a valid Roman numeral in the range [1, 3999].

Think about it first

Hint 1 Map each symbol to its value. Almost every symbol adds its value to a running total — the subtractive pairs are the only exception.
Hint 2 A symbol is subtracted exactly when its value is smaller than the value of the symbol immediately to its right (e.g. the `I` in `IV`). Otherwise it is added.
Hint 3 Scan left to right comparing each symbol with its right neighbor — subtract when strictly smaller, add otherwise. (Scanning right to left works too: compare each symbol with the previous, larger-so-far value.)

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug