Short clean java solution using one easy formula


  • 0
    C
    public int romanToInt(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int[] map = new int[26];
        map['I' - 'A'] = 1;
        map['V' - 'A'] = 5;
        map['X' - 'A'] = 10;
        map['L' - 'A'] = 50;
        map['C' - 'A'] = 100;
        map['D' - 'A'] = 500;
        map['M' - 'A'] = 1000;
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            int cur = map[s.charAt(i) - 'A'];
            sum += cur - 2 * (sum % cur); //the easy formula
        }
        return sum;
    }

Log in to reply
 

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