Simple Java solution


  • 0
        static int toInt(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;
            }   
            throw new IllegalArgumentException();
        }   
    
        public int romanToInt(String s) {
            int[] arr = new int[s.length()];
            for (int i = 0; i < s.length(); i++)
                arr[i] = toInt(s.charAt(i));
            int sum = 0;
            for (int i = 0; i < arr.length; i++)
                sum += (i + 1 < arr.length && arr[i] < arr[i + 1]) ? -arr[i] : arr[i];
            return sum;
        } 
    

Log in to reply
 

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