20/24 ms Simple C solution


  • 1
    C
    int getVal(char c){
        switch(c){
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
        }
    }
    int romanToInt(char* s) {
        int len = strlen(s);
        int sum=0;
        for(int i=0;i<len;i++){
            if(i+1<len && getVal(s[i])<getVal(s[i+1])){
                sum += getVal(s[i+1]) - getVal(s[i]);
                i++;
            }else
                sum += getVal(s[i]);
        }
        return sum;
    }

Log in to reply
 

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