DevPath

← All problems

Roman to Integer

Easy strings · math

Description

Convert a Roman numeral to an integer using subtractive notation (for example IV is 4).

Constraints

1 <= length <= 15

Examples

Input: s = "MCMXCIV"

Output: 1994

Hints (1)
  • If a smaller symbol precedes a larger one, subtract it.

Solutions

Left-to-right comparison. · Time O(n) · Space O(1)

func romanToInt(s string) int {
    values := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    total := 0
    for i := 0; i < len(s); i++ {
        v := values[s[i]]
        if i+1 < len(s) && v < values[s[i+1]] {
            total -= v
        } else {
            total += v
        }
    }
    return total
}

Create a free account to submit solutions, track progress and save problems.

Create account