![]() |
|
[C] Roman Numerals Calculation Example - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Coding (https://sinister.ly/Forum-Coding) +--- Forum: C, C++, & Obj-C (https://sinister.ly/Forum-C-C-Obj-C) +--- Thread: [C] Roman Numerals Calculation Example (/Thread-C-Roman-Numerals-Calculation-Example) |
[C] Roman Numerals Calculation Example - ArkPhaze - 01-26-2014 Just a quick little set of functions I wrote for calculating the numeric value from roman numerals: 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
|