Easy to understand Java solution


  • 0
    M
    public class Solution {
    public int romanToInt(String s) {
        char[] numerals = s.toCharArray();
        int total = 0;
        int pos = 0;
        
        /* case empty string input */
        if(numerals.length == 0)
            return 0;
        
        /* case one character string input */
        if(numerals.length == 1)
            return charToNum(numerals[0]);
            
        /* case string longer than one character */
        while(pos < numerals.length){
            
            /* check if the next character value is greater,
             * if so, add the next char value - current pos value, 
             * and skip these two position;
             * if not, add current char value and move to next. */
            if(pos < numerals.length - 1){
                if(charToNum(numerals[pos+1]) > charToNum(numerals[pos])){
                    total = total + charToNum(numerals[pos+1]) - charToNum(numerals[pos]);
                    pos += 2;
                }else{
                    total = total + charToNum(numerals[pos]);
                    pos += 1;
                }
            }else{
                    total = total + charToNum(numerals[pos]);
                    pos += 1;
            }
        }
        return total;
    }
    
    private int charToNum(char c){
        switch (c) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }
    }

Log in to reply
 

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