如果某一个字母代表的数字大于上一个字母代表的数字小,那么加上这个数字,否则,减去两倍的前一个数字,然后加上这一位数字。
1 public class Solution { 2 private static char[][] chars = {{'I', 'V'}, {'X', 'L'}, {'C', 'D'}, {'M', 'O'}}; 3 private static HashMap<Character, Integer> map = null; 4 private static void init() { 5 map = new HashMap<Character, Integer>(); 6 for (int i = 0; i < 4; i++) { 7 map.put(chars[i][0], (int) Math.pow(10, i)); 8 map.put(chars[i][1], 5 * (int) Math.pow(10, i)); 9 } 10 } 11 public static int romanToInt(String s) { 12 if (map == null) { 13 init(); 14 } 15 int length = s.length(); 16 int result = 0; 17 boolean flag = true; 18 int prev = map.get(s.charAt(0)); 19 for (int i = 1; i < length; i++) { 20 int x = map.get(s.charAt(i)); 21 if (prev >= x) { 22 result += prev; 23 } else { 24 result -= prev; 25 } 26 prev = x; 27 } 28 result += prev; 29 return result; 30 } 31 }