Write a function which, given a string containing roman numerals, returns the equivalent decimal integer or -1 if the string contains an invalid character.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <string.h>

int digitValue(char);
int romanToDecimal(char *);

int main(){
    long int res;
    char roman_Number[1000];

    printf("Enter any roman number (Valid characters are I, V, X, L, C, D, M):  \n");
    scanf("%s",roman_Number);

    if((res = romanToDecimal(roman_Number)) != -1)
        printf("Its decimal value is : %ld", res);

    return 0;
}

int romanToDecimal(char roman_Number[]) {
    int i = 0;
    long int number = 0;
       
    while(roman_Number[i]){
         if(digitValue(roman_Number[i]) < 0){
             printf("Invalid roman digit : %c",roman_Number[i]);
             return -1;
         }
         if((strlen(roman_Number) - i) > 2){
             if(digitValue(roman_Number[i]) < digitValue(roman_Number[i+2])){
                 printf("Invalid roman number");
                 return -1;
             }
         }
         if(digitValue(roman_Number[i]) >= digitValue(roman_Number[i+1]))
             number = number + digitValue(roman_Number[i]);
         else{
             number = number + (digitValue(roman_Number[i+1]) - digitValue(roman_Number[i]));
             i++;
         }
         i++;
    }
    return number;
}

int digitValue(char c){
    int value=0;

    switch(c){
         case 'I': value = 1; break;
         case 'V': value = 5; break;
         case 'X': value = 10; break;
         case 'L': value = 50; break;
         case 'C': value = 100; break;
         case 'D': value = 500; break;
         case 'M': value = 1000; break;
         case '\0': value = 0; break;
         default: value = -1;
    }
    return value;
}

When you compile and execute the above program it produces the following result on Linux:

Sample output for input "X2"

Enter any roman number (Valid characters are I, V, X, L, C, D, M):  
X2
Invalid roman digit : 2

Sample output for input "XX"

Enter any roman number (Valid characters are I, V, X, L, C, D, M):  
XX
Its decimal value is : 20

Brief Explanation

  • The program starts by requesting the user to enter a valid roman number.
  • The inputted roman number is passed to the function romanToDecimal which converts the number to its decimal equivalent.
  • The function makes use of another function digitValue to determine the decimal equivalent of each roman numeral in the string.
  • Each time an invalid roman numeral is found, the function returns -1 to the main function. The final result is printed only if a number other than -1 is returned (The decimal equivalent of the roman numeral).

 

Add comment


Security code
Refresh