Java Solution


  • 0
    A
    class Solution {
        public int romanToInt(String s) {
            char[] c = s.toCharArray();
            int res = 0;
            int cur_max = 1;
            for (int i = c.length - 1; i >= 0; i--) {
                int cur_int = letterToInt(c[i]);
                if (cur_int >= cur_max) {
                    cur_max = cur_int;
                    res += cur_int;
                } else {
                    res -= cur_int;
                }
            }
            return res;
        }
        public int letterToInt(char x) {
            switch (x) { 
                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.