A C solution(easy to understand)


  • 1

    Just use a table to store the weight of each Roman numeral

    int romanToInt(char* s) {
        int weight[256] = {0}; // store weights of I,V,X,L,C,D,M
        weight['I'] = 1;
        weight['V'] = 5;
        weight['X'] = 10;
        weight['L'] = 50;
        weight['C'] = 100;
        weight['D'] = 500;
        weight['M'] = 1000;
        int weight_pre = 0;
        int i = strlen(s) - 1;
        int num = 0;
        while(i >= 0) {
            if(weight[s[i]] >= weight_pre)
                num += weight[s[i]];
            else
                num -= weight[s[i]];
            weight_pre = weight[s[i--]];
        }
        return num;
    }
    

Log in to reply
 

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