Simple Java Solution 93ms


  • 0
    D
    public class Solution {
        public int romanToInt(String s) {
            int sum = 0;
            int current = 0;
            int previous = 0;
            if (s == null){return sum;}
            for (int i =0; i<s.length();i++){
                char c = s.charAt(i);
                switch(c){
                case 'I' : 
                    current =1 ; 
                    sum = sum + current;
                    break;
                case 'V' :
                    current =5 ;
                    if (previous<current && i!=0){sum = sum + current - 2*previous;}
                    else{sum = sum + current;}
                    break;
                case 'X' :
                    current = 10 ;
                    if (previous<current && i!=0){sum = sum + current - 2*previous;}
                    else{sum = sum + current;}
                    break;
                case 'L' :
                    current = 50;
                    if (previous<current && i!=0){sum = sum + current - 2*previous;}
                    else{sum = sum + current;}
                    break;
                case 'C' :
                    current = 100 ;
                    if (previous<current && i!=0){sum = sum + current - 2*previous;}
                    else{sum = sum + current;}
                    break;
                case 'D' : 
                    current = 500 ;
                    if (previous<current && i!=0){sum = sum + current - 2*previous;}
                    else{sum = sum + current;}
                    break;
                case 'M' : 
                    current = 1000;
                    if (previous<current && i!=0){sum = sum + current - 2*previous;}
                    else{sum = sum + current;}
                    break;
                default:
                    break;
                }
     
                previous = current;
            }
            return sum;
    
        }
    }

Log in to reply
 

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