Coding problem · Easy · Basics
Roman Numerals to Integer
Easy Algorithms & data structures
Convert a valid Roman numeral s (1 to 3999) to an integer. Symbols: I=1, V=5, X=10, L=50, C=100, D=500, M=1000.
A smaller symbol before a larger one is subtracted: IV = 4, IX = 9, XL = 40, CM = 900.
Example 1
Input: s = "III" Output: 3
Example 2
Input: s = "LVIII" Output: 58
Example 3
Input: s = "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90, IV = 4
Hints
Hint 1
Look up each symbol's value.
Hint 2
If a symbol is smaller than the next one, subtract it; otherwise add it.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
Scan left to right. Add each value, except when it's smaller than the value after it, in which case subtract it. That single rule handles all six subtractive pairs.
Reference solution
function romanToInt(s) {
const v = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
let total = 0;
for (let i = 0; i < s.length; i++) {
const cur = v[s[i]], next = v[s[i + 1]] ?? 0;
total += cur < next ? -cur : cur;
}
return total;
}
function romanToInt(s: string): number {
const v: Record<string, number> = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
let total = 0;
for (let i = 0; i < s.length; i++) {
const cur = v[s[i]], next = v[s[i + 1]] ?? 0;
total += cur < next ? -cur : cur;
}
return total;
}
def roman_to_int(s: str) -> int:
v = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
total = 0
for i, ch in enumerate(s):
nxt = v[s[i + 1]] if i + 1 < len(s) else 0
total += -v[ch] if v[ch] < nxt else v[ch]
return total
<?php
function romanToInt(string $s): int
{
$v = ['I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000];
$total = 0;
for ($i = 0; $i < strlen($s); $i++) {
$cur = $v[$s[$i]];
$next = $i + 1 < strlen($s) ? $v[$s[$i + 1]] : 0;
$total += $cur < $next ? -$cur : $cur;
}
return $total;
}
class Solution {
public int romanToInt(String s) {
java.util.Map<Character, Integer> v = java.util.Map.of('I', 1, 'V', 5, 'X', 10, 'L', 50, 'C', 100, 'D', 500, 'M', 1000);
int total = 0;
for (int i = 0; i < s.length(); i++) {
int cur = v.get(s.charAt(i));
int next = i + 1 < s.length() ? v.get(s.charAt(i + 1)) : 0;
total += cur < next ? -cur : cur;
}
return total;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy