Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question.
Solution:
Tips:
implement it using recursion, just for practice it.
Java Code:
public class Solution {
public int romanToInt(String s) {
// I/1 V/5 X/10 L/50 C/100 D/500 M/1000
Map<Character, Integer> table = new HashMap<>();
table.put('I', 1);
table.put('V', 5);
table.put('X', 10);
table.put('L', 50);
table.put('C', 100);
table.put('D', 500);
table.put('M', 1000);
return romanToInt(s, 0, table);
}
public int romanToInt(String s, int begin, Map<Character, Integer> table) {
// I/1 V/5 X/10 L/50 C/100 D/500 M/1000
// left only can keep one, rigth can keep two for V L D
if (begin + 1 == s.length()) {
return table.get(s.charAt(begin));
}
if (begin == s.length()) {
return 0;
}
int left = table.get(s.charAt(begin));
int right = table.get(s.charAt(begin + 1));
return left >= right ? left + romanToInt(s, begin + 1, table) : right - left + romanToInt(s, begin + 2, table);
}
}