Roman to Integer


  • 0
    S

    when I submit I got a wrong answer saying
    Input: "MMMCXCI"
    Output: 3201
    Expected: 3191

    but when I run code for same input it says your answer is 3191 and expected answer is 3191
    what is this issue?
    here is my code

    int romanToInt(char* s) {
        int num=0,i=0,a,b;
        if(s[i]=='I')
            a = 1;
        else if(s[i]=='V')
            a = 5;
        else if(s[i]=='X')
            a = 10;
        else if(s[i]=='L')
            a=50;
        else if(s[i]=='C')
            a = 100;
        else if(s[i]=='D')
            a = 500;
        else if(s[i]=='M')
            a=1000;
        i++;
        while(s[i]!='\0'){
            if(a==-1){
                if(s[i]=='I')
                    a = 1;
                else if(s[i]=='V')
                    a = 5;
                else if(s[i]=='X')
                   a = 10;
                else if(s[i]=='L')
                    a=50;
                else if(s[i]=='C')
                    a = 100;
                else if(s[i]=='D')
                    a = 500;
                else if(s[i]=='M')
                    a=1000;
                i++;
            }
            if(s[i]=='I')
                b = 1;
            else if(s[i]=='V')
                b = 5;
            else if(s[i]=='X')
                b = 10;
            else if(s[i]=='L')
                b = 50;
            else if(s[i]=='C')
                b = 100;
            else if(s[i]=='D')
                b = 500;
            else if(s[i]=='M')
                b = 1000;
            if(a<b){
                num = num + b-a;
                a = -1;
                b = 0;
            }
            else{ 
                num = num + a;
                a = b;
            }
            i++;
        }
        if(num == 0)
            return a;
        return num+b;
    }
    

Log in to reply
 

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