Roman to Integer
EasySubtract when a smaller numeral precedes a larger
Add up the letter values, but subtract when a smaller value sits before a bigger one (like IV = 4).
The idea
Scan left to right. Normally add each numeral's value, but if a numeral is smaller than the one after it (like IV or IX), subtract it instead.
M
C
M
X
C
I
V
0
1
2
3
4
5
6
total0
Step 1 of 9. Add each numeral, but if a smaller numeral sits before a larger one (like IV or CM), subtract it instead. Values: M, C, M, X, C, I, V. total 0.
1/9
Optimal
timeO(n)spaceO(1)
Subtract on ascending pairs.
1let total = 0;2for (let i = 0; i < s.length; i++) {3 const cur = val[s[i]], next = val[s[i + 1]] ?? 0;4 total += cur < next ? -cur : cur;5}6return total;Input
- array
- [M, C, M, X, C, I, V]
Memory
- i
- —
Output
- total
- 0
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- s = "III"
- Output:
- 3
- Explanation:
- Three 1s make 3.
Example 2
- Input:
- s = "LVIII"
- Output:
- 58
- Explanation:
- 50 + 5 + 3 = 58.
Example 3
- Input:
- s = "MCMXCIV"
- Output:
- 1994
- Explanation:
- 1000 + 900 + 90 + 4 = 1994.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.