Visualize

Pattern visualizer

Roman to Integer

Scan left to right. If the current roman value is less than the next value, subtract it (subtractive notation like IV=4, IX=9). Otherwise add it. This single pass computes the total. Animated on: Given roman="MCMXCIV", convert to integer (1994).

Left-to-right scan with subtractive notation

time O(n)space O(1)step 1 / 8
M
[0]
C
[1]
M
[2]
X
[3]
C
[4]
I
[5]
V
[6]
line 4

i=0: s[0]='M', cur=1000. i+1<7 && 1000 < values[s[1]]=values['C']=100? No. Add cur: total=1000. Running total: 1000.

Pseudocode
1FUNCTION romanToInt(s):
2 values = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 }
3 total = 0
4 FOR i from 0 to length of s - 1:
5 cur = the value of roman letter s[i]
6 IF there is a next letter and cur < the value of s[i + 1]:
7 subtract cur from total
8 ELSE:
9 add cur to total
10 END IF
11 END FOR
12 RETURN total
13END FUNCTION

← / → step · space play · Home restart

Where to practice Strings