← DiffPush

Roman to Integer

Standard Bar Strings · Medium O(n) · O(1)

Decoding the Engraver's Numeral Bands

A heritage engraving workshop receives restoration orders whose dates are carved as Roman numeral bands, and the CNC controller needs plain integers before it can program a job. The shop follows the standard convention: a smaller symbol placed before a larger one is subtractive, everything else adds up. The controller parses the band left to right, adding symbol values and flipping to subtraction whenever a smaller symbol precedes a larger.

Input: A string s representing a Roman numeral, using the symbols I, V, X, L, C, D and M.

Output: The integer value the numeral denotes.

Constraints

Examples

Example 1

Input: {"s":"III"}
Output: 3
Three additive I symbols, no subtractive pairs.

Example 2

Input: {"s":"LVIII"}
Output: 58
L is 50, V is 5 and III is 3; no symbol precedes a larger one, so everything adds.

Solve this in your browser →

Also on LeetCode ↗