Roman To Numbers
This algorithm converts roman numerals to decimal numbers.
/*****Please include following header files*****/
// stdint.h
/***********************************************/
void RTrim(char* str) {
size_t n;
n = strlen(str);
while (n > 0 && isspace((unsigned char)str[n - 1])) {
n--;
}
str[n] = '\0';
}
void LTrim(char* str) {
size_t n;
n = 0;
while (str[n] != '\0' && isspace((unsigned char)str[n])) {
n++;
}
memmove(str, str + n, strlen(str) - n + 1);
}
void Trim(char* str) {
RTrim(str);
LTrim(str);
}
int RomanToNumber(char romanChar) {
switch (romanChar)
{
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
break;
}
return 0;
}
int RomanToNumbers(char* roman) {
roman = _strupr(roman);
Trim(roman);
if (roman == "N") return 0;
int ptr = 0;
int total = 0;
int valuesCount = 0;
int maxDigit = 1000;
int romanLen = strlen(roman);
while (ptr < romanLen)
{
char numeral = roman[ptr];
int digit = RomanToNumber(numeral);
int nextDigit = 0;
if (ptr < romanLen - 1)
{
char nextNumeral = roman[ptr + 1];
nextDigit = RomanToNumber(nextNumeral);
if (nextDigit > digit)
{
maxDigit = digit - 1;
digit = nextDigit - digit;
ptr++;
}
}
total += digit;
ptr++;
}
return total;
}
Example
char data[] = "CDXIX";
int value = RomanToNumbers(data);
Output
419