Roman numeral to integer
Easy TimeO(n) SpaceO(1)
Roman numerals are read by adding their symbols left to right — I 1, V 5, X 10, L 50, C 100, D 500, M 1000 — except that a smaller symbol placed immediately before a larger one is taken away instead, so "IV" is 4 rather than 6. Given a well-formed numeral s, return the number it stands for. Only six such pairs exist: IV, IX, XL, XC, CD and CM.
Examples
Example 1
- Input
- s = "MCMXCIV"
- Output
1994M1000,CM900,XC90,IV4 →1000 + 900 + 90 + 4.
Example 2
- Input
- s = "LVIII"
- Output
58L50,V5,III3, with nothing taken away →50 + 5 + 3.
The Code
function romanToInt(s) {
const value = { 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 current = value[s[i]];
const next = value[s[i + 1]] || 0;
if (current < next) total -= current;
else total += current;
}
return total;
}
romanToInt("MCMXCIV");Done
More like this
All math & numbers examples (8) →- Prime check Only test odd divisors, and only up to the square root.
- Prime sieve Cross out every multiple; whatever survives is prime.
- Happy number Sum the squared digits until you reach 1 — or start repeating.
- Integer → Roman Greedily take the largest symbol that still fits.
- Collatz Halve it if even, triple-plus-one if odd — always reaches 1.
- Newton’s sqrt Average your guess with n over your guess; it converges fast.