Explanatory Java code


  • 0
    L
        static final Map<Character,Integer> map = new HashMap<>();
        static {
            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);
        }
        public int romanToInt(String s) {
    //Number	4	9	40	90	400	900
    //Notation	IV	IX	XL	XC	CD	CM
            char prev='\0';
            int number = 0;
            for(char c : s.toCharArray()) {
                number += map.get(c);
                if(map.get(c)%5==0) {
                    //check the last character.
                    if((c=='V' || c=='X') && prev=='I') {
                        number -=2; //since already added; subtract twice.
                    }
                    else if((c=='L' || c=='C') && prev=='X') {
                        number -=20;
                    }
                    else if((c=='D' || c=='M' ) && prev=='C') {
                        number -=200;
                    }
                }
                prev = c;
            }
            return number;
        }
    

Log in to reply
 

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