Leetcode - Roman to Integer (Java)
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Analysis
The rules to transfer a roman to an integer can be understood using the following examples:
|
1 |
I == 1 II == 2 III == 3 IV == 4 V == 5 VI == 6 VII == 7 VIII == 8 IX = 9 X== 10, XI == 11, XL == 40, L == 50, LX == 60 |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public int romanToInt(String s) { Map<Character, Integer> dict = new HashMap<>(); dict.put('I', 1); dict.put('V', 5); dict.put('X', 10); dict.put('L', 50); dict.put('C', 100); dict.put('D', 500); dict.put('M', 1000); char pre = s.charAt(0); char cur; int preValue = dict.get(pre); int curValue; int res = preValue; int i = 1; while(i < s.length()){ cur = s.charAt(i); curValue = dict.get(cur); res += curValue; if(curValue > preValue) { res -= 2 * preValue; } preValue = curValue; i++; } return res; } |











