DEV Community

Discussion on: Leetcode - Roman to Integer (with JavaScript)

Collapse
 
jungus80 profile image
Jungus80

why i++ in the if condition ?

Collapse
 
developer3027 profile image
Developer3027

in Roman numbers a situation where you have a lower value proceeding a higher value like "IV" you subtract. In the case of "IV" you subtract I = 1 from V = 5 to get four. The current and next variables are created to evaluate just this condition. If condition is found then do the math and set the new result. Seeing as you used two of the strings, you need to advance one to begin the next evaluation. Notice that next is i+1. If you don't advance after the subtraction eval then the loop count will fall one behind and the math is wrong. Hope this helps.

Collapse
 
moosorkh profile image
Fortis Irdmousa

Because if the current symbol is smaller than the next one, for instance, 'CM', it means that the number is 900 (100 subtracted from 1000). Therefore, the index must jump one place ahead of the current symbol so that the loop avoids mistakenly including the 'M' from 'CM' in the addition. I hope it makes sense.