Easy to read 10ms Java solution


  • 3
    M
    public class Solution {
        public int romanToInt(String s) {
            s = s.toUpperCase();
            
            int negative = 0;
            int positive = 0;
            for (int i = 0; i < s.length(); i++)
            {
                int curLetter = singleLetterValue(s.charAt(i));
                if (i + 1 < s.length() && curLetter < singleLetterValue(s.charAt(i+1) ))
                {
                    negative += curLetter;
                } 
                else
                {
                    positive += curLetter;
                }
            }
            return positive - negative;
        }
        
        public int singleLetterValue(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;
            }
            return -1;
        }
    }

Log in to reply
 

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