Int array as roman number mapping to solve it -- Squeezing size of the int array to 22


  • 0
    L
    public int RomanToInt(string s) {
        int[] roman = new int['X' - 'C' + 1];
        roman['I' -'C'] = 1; roman['V' -'C'] = 5; roman['X' -'C'] = 10; roman['L' -'C'] = 50;
        roman['C' -'C'] = 100; roman['D' -'C'] = 500; roman['M' -'C'] = 1000;
        int sum = 0;
        for(int i = 0; i < s.Length; i++)
            if(i < s.Length - 1 && roman[s[i + 1] -'C'] > roman[s[i] -'C'])
                sum -= roman[s[i] -'C'];
            else sum += roman[s[i] -'C'];
        return sum;
    }

Log in to reply
 

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