Roman to Integer (C)


  • 0
    P
    typedef struct _RomaInt{ char Roma; int  num;}RomaInt;
    
        RomaInt Roma_I = {'I', 1};
        RomaInt Roma_V = {'V', 5};
        RomaInt Roma_X = {'X', 10};
        RomaInt Roma_L = {'L', 50};
        RomaInt Roma_C = {'C', 100};
        RomaInt Roma_D = {'D', 500};
        RomaInt Roma_M = {'M', 1000};
    
    int romanToInt(char* s) {
        int PreNum = 0, CurrNum =0, n = 0;
        char Roma;
        int sl = strlen(s) ;
    
        for (int i=0; i <= sl; i++){
            if (CurrNum !=0)
                PreNum = CurrNum;
            Roma = s[i];
            switch (Roma){
            case 'I':
                CurrNum = Roma_I.num;
                break;
            case 'V':
                CurrNum = Roma_V.num;
                break;
            case 'X':
                CurrNum = Roma_X.num;
                break;
            case 'L':
                CurrNum = Roma_L.num;
                break;
            case 'C':
                CurrNum = Roma_C.num;
                break;
            case 'D':
                CurrNum = Roma_D.num;
                break;
            case 'M':
                CurrNum = Roma_M.num;
                break;
            default:
                printf("null\n");
            }//switch
    
            if(PreNum != 0){
                if(PreNum < CurrNum){
                    n = n + CurrNum - PreNum;
                    PreNum = CurrNum = 0;
                }
                else
                    n = n + PreNum;
            }
        }//for
        return n;
    }

Log in to reply
 

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