• Question Description
    13. Roman to Integer_java13. Roman to Integer_力扣_02
  • My Key
package LeetCode;
import java.util.HashMap;
import java.util.Map;
public class Test {

public static void main(String[] args) {
System.out.println(romanToInt("IIII"));
}

public static int romanToInt(String s) {
int rev = 0;

Map<Character, Integer> eleMap = new HashMap<Character, Integer>();
eleMap.put('I', 1);
eleMap.put('V', 5);
eleMap.put('X', 10);
eleMap.put('L', 50);
eleMap.put('C', 100);
eleMap.put('D', 500);
eleMap.put('M', 1000);

for (int i = s.length()-1; i >= 0; i--) {
if (i == s.length()-1) {
rev = (Integer) eleMap.get(s.charAt(i));
continue;
}
if ((Integer)eleMap.get(s.charAt(i)) >= (Integer)eleMap.get(s.charAt(i+1))) {
rev += (Integer) eleMap.get(s.charAt(i));
} else {
rev -= (Integer) eleMap.get(s.charAt(i));
}
}

return rev;
}
}