Leetcode – Roman to Integer (Java)

Tags: , ,

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.


The rules to transfer a roman to an integer can be understood using the following examples:

So for any two Roman letters in the form: Left Right

if the left is smaller than the right, the result will be right – left.

if the left is larger or equal to the right, the result will right + left.

See this link for more examples of the roman numbers.

We can scan the roman letters, and add the current value to the final result. If the previous value is smaller than current one, based on the rule,  the previous value should be decreased from the result. As we already add the previous value to the result, we need to minus 2 * previousValue. 

The following is the Java Implementation.