Skip to content

Instantly share code, notes, and snippets.

@sixthgear
Created July 24, 2012 23:02
Show Gist options
  • Select an option

  • Save sixthgear/3173230 to your computer and use it in GitHub Desktop.

Select an option

Save sixthgear/3173230 to your computer and use it in GitHub Desktop.
Roman Numerals
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct symbol_table {
int num;
char sym[3];
};
struct symbol_table symbols[] = {
{1000, "M"},
{900, "CM"},
{500, "L"},
{400, "CD"},
{100, "C"},
{90, "XC"},
{50, "L"},
{40, "XL"},
{10, "X"},
{9, "IX"},
{5, "V"},
{4, "IV"},
{1, "I"}
};
int
roman_to_arabic(const char *s)
{
int total, num, s_len, p_len;
struct symbol_table *sym;
char buf[3];
char *p;
s_len = strlen(s);
p = (char *) s;
p_len = 2;
total = 0;
while (p < s+s_len) {
num = 0;
strncpy(buf, p, p_len);
buf[p_len] = '\0';
/* check if the symbol is in the table */
for(sym=symbols; sym<symbols+13 && !num; sym++) {
if (strcmp(buf, sym->sym) == 0)
num = sym->num;
}
if (num) {
/* we found a symbol */
total += num;
p += p_len;
p_len = 2;
continue;
} else if (--p_len == 0) {
/* didn't find a symbol, move to the next one */
printf("invalid symbol! %s\n", buf);
p_len = 2;
p++;
}
}
return total;
}
void
arabic_to_roman(int d, char *buf)
{
struct symbol_table *sym;
buf[0] = '\0';
while (d > 0) {
for(sym=symbols; sym<symbols+13; sym++) {
if (d >= sym->num) {
strcat(buf, sym->sym);
d -= sym->num;
break;
}
}
}
}
int
main(int argc, char** argv)
{
char buf[50];
int i;
for (i=1; i<=3999; i++) {
arabic_to_roman(i, buf);
printf("%5d -> %-20s", i, buf);
printf("%s -> %d\n", buf, roman_to_arabic(buf));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment