Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don’t need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered “MCMXC” (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered “MMVIII” (2000 = MM, 8 = VIII). The Roman numeral for 1666, “MDCLXVI”, uses each letter in descending order.
Example:
solution('XXI'); // should return 21
The problem link is here.
Solution:
#include <string.h>
int roman_val(char roman)
{
int val = 0;
switch (roman)
{
case 'I':
return val = 1;
break;
case 'V':
return val = 5;
break;
case 'X':
return val = 10;
break;
case 'L':
return val = 50;
break;
case 'C':
return val = 100;
break;
case 'D':
return val = 500;
break;
case 'M':
return val = 1000;
break;
}
return val;
}
unsigned decode_roman(const char *roman_number)
{
unsigned long len = strlen(roman_number);
unsigned i, n, m, value = 0;
for (i = 0; i < len; i++)
{
n = roman_val(roman_number[i]);
m = roman_val(roman_number[i + 1]);
if (n >= m)
value += n;
else if (n < m)
value += (m - n), i++;
}
return value;
}