Java Clean Code


  • 2
    C
    public class Solution {
        
        private static Map<Character, Integer> romanMap;
        
        static {
            romanMap = new HashMap<>();
            romanMap.put('I', 1);
            romanMap.put('V', 5);
            romanMap.put('X', 10);
            romanMap.put('L', 50);
            romanMap.put('C', 100);
            romanMap.put('D', 500);
            romanMap.put('M', 1000);
        }
        
        public int romanToInt(String s) {
            char[] charArr = s.toCharArray();
            int sum = 0;
            for (int i = 0; i < charArr.length; i++) {
                int currentValue = romanMap.get(charArr[i]);
                if (isSubstractiveNotation(charArr, i)) {
                    int nextValue = romanMap.get(charArr[i + 1]);
                    sum += nextValue - currentValue;
                    i++;
                } else {
                    sum += currentValue;
                }
            }
            return sum;
        }
        
        /**
         * See https://en.wikipedia.org/wiki/Subtractive_notation
         */
        private boolean isSubstractiveNotation(char[] charArr, int index) {
            return (index < charArr.length - 1
                && romanMap.get(charArr[index + 1]) > romanMap.get(charArr[index]));
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.