Solution with intuitive handling for subtractive notation


  • 0
    N
    public int romanToInt(String s) {
            
            int prevCharVal = 0;
            int currCharVal = 0;
            int totalVal = 0;
            
            String t = s.toLowerCase();
            for(int i = 0; i < t.length(); i++) {
                
                currCharVal = getCharVal(t.charAt(i));
                // check for 'substractive notation'
                // i.e. when lower value character appears before higher value
                if (prevCharVal > 0 && prevCharVal < currCharVal) {
                    // subtract twice since we added it in prev iteration
                    totalVal -= 2*prevCharVal;
                }
                totalVal += currCharVal;
                prevCharVal = currCharVal;
            }
            return totalVal;
        }
        
        private static int getCharVal(char c) {
            
            switch(c) {
                case 'm': return 1000;
                case 'd': return 500;
                case 'c': return 100;
                case 'l': return 50;
                case 'x': return 10;
                case 'v': return 5;
                case 'i': return 1;
                default:
                    return -1;
            }
        }

Log in to reply
 

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