My C solution, 62ms


  • 0
    1
    int romanToInt(char* s) {
        int len = (int) strlen(s);
        int* s_int = malloc(len*sizeof(int));
        for(int i=0;i<len;i++){
            if(s[i] == 'M')
                s_int[i] = 1000;
            else if(s[i] == 'D')
                s_int[i] = 500;
            else if(s[i] == 'C')
                s_int[i] = 100;
            else if(s[i] == 'L')
                s_int[i] = 50;
            else if(s[i] == 'X')
                s_int[i] = 10;
            else if(s[i] == 'V')
                s_int[i] = 5;
            else
                s_int[i] = 1;
        }
        int result = 0;
        int index = 0;
        while(index < len){
            if(index != len-1){
                if(s_int[index+1] > s_int[index]){
                    result = result + s_int[index+1]-s_int[index];
                    index = index + 2;
                }
                else {
                    result = result + s_int[index];
                    index++;
                }
            }
            else {
                result = result + s_int[index];
                index++;
            }
        }
        return result;
    }
    

Log in to reply
 

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