Input is guaranteed to be within the range from 1 to 3999.
public int RomanToInt(String s) { HashMapromanIntMap = new HashMap (); romanIntMap.put('M', 1000); romanIntMap.put('D', 500); romanIntMap.put('C', 100); romanIntMap.put('L', 50); romanIntMap.put('X', 10); romanIntMap.put('V', 5); romanIntMap.put('I', 1); int num = 0; for(int i = 0; i < s.length(); i++){ int value = romanIntMap.get(s.charAt(i)); if( (i != s.length() - 1) && value < romanIntMap.get(s.charAt(i+1))){ num -= value; continue; } num +=value; } return num; }
No comments:
Post a Comment