Skip to content

Instantly share code, notes, and snippets.

@cls
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save cls/0113b457661f16ae8012 to your computer and use it in GitHub Desktop.

Select an option

Save cls/0113b457661f16ae8012 to your computer and use it in GitHub Desktop.
Roman numeral parser
#include <stdio.h>
enum { I, V, X, L, C, D, M, StackSize };
const int values[] = { 1, 5, 10, 50, 100, 500, 1000 };
int
unroman(const char *s)
{
int stack[StackSize];
int i, n, sum;
for(i = 0; i < StackSize; i++)
stack[i] = 0;
for(; *s != '\0'; s++) {
switch(*s) {
case 'I': n = I; break;
case 'V': n = V; break;
case 'X': n = X; break;
case 'L': n = L; break;
case 'C': n = C; break;
case 'D': n = D; break;
case 'M': n = M; break;
default:
return -1;
}
sum = values[n];
for(i = 0; i < n; i++) {
sum -= stack[i];
stack[i] = 0;
}
stack[n] += sum;
}
sum = 0;
for(i = 0; i < StackSize; i++)
sum += stack[i];
return sum;
}
int
main(int argc, char **argv)
{
int i, n;
for(i = 1; i < argc; i++) {
n = unroman(argv[i]);
if(n < 0) {
fprintf(stderr, "%s: invalid numeral: %s\n", argv[0], argv[i]);
continue;
}
printf("%s = %d\n", argv[i], n);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment