[JAVA] simple solution


  • 0
    public int romanToInteger(String s) {
            Map<String, Integer> dictionary = new HashMap<>();
            dictionary.put("I", 1);
            dictionary.put("V", 5);
            dictionary.put("X", 10);
            dictionary.put("L", 50);
            dictionary.put("C", 100);
            dictionary.put("D", 500);
            dictionary.put("M", 1000);
    
            int length = s.length();
            int sum = dictionary.get(String.valueOf(s.charAt(length-1)));
    
            for (int i = (length -1); i > 0; i--) {
                int tail = dictionary.get(String.valueOf(s.charAt(i)));
                int head = dictionary.get(String.valueOf(s.charAt(i-1)));
    
                if(tail <= head){
                    sum = sum + head;
                } else {
                    sum = sum - head;
                }
            }
    
            return sum;
        }

Log in to reply
 

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