Easy java solution


  • 2
     public static int romanToInt(String s) {
        int res = 0;
        if (s == null || s.length() == 0) return res;
        int len = s.length() - 1;
        for (int i = len; i >= 0 ; i--) {
            char c = s.charAt(i);
            switch (c) {
                case 'M':
                res += 1000;
                break;
                case 'D':
                res += 500;
                break;
                case 'C':
                res += 100 * (res >= 500 ? -1 : 1); // >= not just >
                break;
                case 'L':
                res += 50;
                break;
                case 'X':
                res += 10 * (res >= 50 ? -1 : 1); // >= not just >
                break;
                case 'V':
                res += 5;
                break;
                case 'I':
                res += (res >= 5 ? -1 : 1); // >= not just >
                break;
                default:
                break;
            }
        }
        return res;
    }

Log in to reply
 

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