Roman to Integer
Easy strings · math
Description
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
}
Left-to-right comparison. · Time O(n) · Space O(1)
function romanToInt(s) {
const map = { 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 v = map[s[i]];
total += (i + 1 < s.length && v < map[s[i + 1]]) ? -v : v;
}
return total;
}
Left-to-right comparison. · Time O(n) · Space O(1)
function romanToInt($s) {
$map = ['I'=>1,'V'=>5,'X'=>10,'L'=>50,'C'=>100,'D'=>500,'M'=>1000];
$total = 0; $n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$v = $map[$s[$i]];
if ($i + 1 < $n && $v < $map[$s[$i + 1]]) { $total -= $v; } else { $total += $v; }
}
return $total;
}
Left-to-right comparison. · Time O(n) · Space O(1)
def romanToInt(s):
values = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
total = 0
for i, c in enumerate(s):
v = values[c]
if i + 1 < len(s) and v < values[s[i + 1]]:
total -= v
else:
total += v
return total
Left-to-right comparison. · Time O(n) · Space O(1)
function romanToInt(s: string): number {
const map: 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 v = map[s[i]];
total += (i + 1 < s.length && v < map[s[i + 1]]) ? -v : v;
}
return total;
}
Create a free account to submit solutions, track progress and save problems.
Create account