Why does input “III” produce an unexpected result?

  Kiến thức lập trình

The function takes roman numerals and returns the sum. Program seems to struggle on inputs containing only “I”.

int romanToInt(char* s){
    long long int values[256];
    int digit[256];
    values['M'] = 1000;
    values['D'] = 500;
    values['C'] = 100;
    values['L'] = 50;
    values['X'] = 10;
    values['V'] = 5;
    values['I'] = 1;
    long long int total = 0;
    int i = 0;
    for(int j = 0; j < strlen(s); j++){
        char numeral = s[j];
        digit[j] = values[numeral];
    }
    
    while(i < strlen(s){
        if(digit[i] < digit[i + 1]){
            total = total + (digit[i + 1] - digit[i]);
            i += 2;
        }
        else{
            total = total + digit[i];
            i++;
        }
    }
    return total;
}

I changed the while loop from

while(digit[i] != 0)

to

while(i < strlen(s))

which worked to improve a number of test cases but I am not exactly sure why. From what I have been able to gather, the initial if statement is true for values containing only “I”. For example, “CCC” correctly returns 300 but “III” returns 51.

LEAVE A COMMENT