My 50ms C solution, time complexity O(n). Only scans one time and uses two extra variables.


  • 0
    F
    int romanToInt(char* s) {
        int sum = 0;
        char prev = ' ';
        while (*s != '\0') {
            switch (*s) {
                case 'I':
                    sum += 1;
                    break;
                case 'V':
                    sum += 5;
                    if (prev == 'I') sum-=2;
                    break;
                case 'X':
                    sum += 10;
                    if (prev == 'I') sum-=2;
                    break;
                case 'L':
                    sum += 50;
                    if (prev == 'X') sum-=20;
                    break;
                case 'C':
                    sum += 100;
                    if (prev == 'X') sum-=20;
                    break;
                case 'D':
                    sum += 500;
                    if (prev == 'C') sum-=200;
                    break;
                case 'M':
                    sum += 1000;
                    if (prev == 'C') sum-=200;
                    break;
            }
            prev = *(s++);
        }
        return sum;
    }
    

Log in to reply
 

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