[C] Roman Numerals Calculation Example 01-26-2014, 12:21 AM
#1
Just a quick little set of functions I wrote for calculating the numeric value from roman numerals:
It will be a nice addition to converting roman numerals to proper form; project euler question I had seen in the past.
*edit: Updated supported roman chars.
Happy MMXIV
Code:
#include <stdio.h>
// #include <stdlib.h>
#include <stdbool.h>
#include <string.h>
static char _roman_chars[] = "IVXLCDMvxlcdm";
static int _numerals[] = {1, 5, 10, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, 500000, 1000000};
int get_roman_numeric_value(char numeral)
{
char *p = strchr(_roman_chars, numeral);
if (p != NULL) return _numerals[p - _roman_chars];
return -1;
}
int get_int_from_roman(char *roman)
{
size_t len = strlen(roman);
if (len < 1) return -1;
int result = get_roman_numeric_value(roman[0]);
for (size_t i = 1; i < len; ++i)
{
int num = get_roman_numeric_value(roman[i]);
int prev = get_roman_numeric_value(roman[i-1]);
if (num < 0 || prev < 0) return -1;
// printf("%d\n", num);
if (prev < num)
result = result - (2 * prev) + num;
else
result += num;
}
return result;
}
bool valid_roman_number(char *roman)
{
return strlen(roman) == strspn(roman, _roman_chars);
}
int main()
{
char roman[] = "MCXIV";
if (!valid_roman_number(roman))
{
printf("Invalid roman number specified.\n");
return 1;
}
int val = get_int_from_roman(roman);
if (val < 0)
{
printf("An error ocurred when trying to get the numeric value from the roman format.\n");
return 1;
}
printf("Roman Value: %d\n", val);
}It will be a nice addition to converting roman numerals to proper form; project euler question I had seen in the past.
*edit: Updated supported roman chars.
Happy MMXIV
ArkPhaze
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]
![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)