Roman to Integer

LeetCode Q 13 - Roman to Integer

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Example 1: Input: "III" ; Output: 3

Example 2: Input: "IV" ; Output: 4

Example 3: Input: "IX" ; Output: 9

Example 4: Input: "LVIII" ; Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5: Input: "MCMXCIV" ; Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Solution

Code:

public int romanToInt(String s) {
  Map<Character, Integer> map = new HashMap<>();
  map.put('I', 1);    map.put('V', 5);
  map.put('X', 10);   map.put('L', 50);
  map.put('C', 100);  map.put('D', 500);
  map.put('M', 1000);
  
  int res = map.get(s.charAt(s.length() - 1));
  for (int i = s.length() - 2; i >= 0; i--) {
    if (map.get(s.charAt(i)) >= map.get(s.charAt(i + 1)))
      res += map.get(s.charAt(i));
    else
      res -= map.get(s.charAt(i));
  }
  return res;
}

   Reprint policy


《Roman to Integer》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC