public int romanToInt(String s) {
//put all the symbols and numbers in the hashmap
int[] numbers = {1000, 500, 100, 50, 10, 5, 1};
char[] symbols = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < numbers.length; i++) {
map.put(symbols[i], numbers[i]);
}
//Calculate the integer
char[] charArr = s.toCharArray();
int result = map.get(charArr[s.length() - 1]);
for (int i = 0; i < s.length()-1; i++) {
result += map.get(charArr[i])
*(map.get(charArr[i]) >= map.get(charArr[i+1]) ? 1 : -1);
}
return result;
}
No comments:
Post a Comment