8ms Java solution


  • 0
    K
    public int romanToInt(String s) {
            int result = 0;
            int prev = Integer.MAX_VALUE;
            for(int i = 0; i < s.length(); i++){
                int number = 0;
                switch(s.charAt(i)){
                    case 'I' : number = 1; break;
                    case 'V' : number = 5; break;
                    case 'X' : number = 10; break;
                    case 'L' : number = 50; break;
                    case 'C' : number = 100; break;
                    case 'D' : number = 500; break;
                    case 'M' : number = 1000; break;
                }
                result += number;
                if(prev < number)
                    result -= (2*prev);
                prev = number;
            }
            return result;
        }

  • 0
    K

    If value of the previous character was less than the current character you want to subtract it from the sum instead of adding, so multiply by 2.


Log in to reply
 

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