Last active
October 11, 2019 21:12
-
-
Save kristopherjohnson/1bb844422a9f2e600bd73d893eccd9f2 to your computer and use it in GitHub Desktop.
C program to convert Roman numerals to integer values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
rn: rn.c | |
test: rn | |
./rn I IV V VI IX X XI XIV XIX XCIX CI MCMLXVII MD MDC MCD MM | |
.PHONY: test |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <limits.h> | |
static int romanLetterValue(char letter) | |
{ | |
switch (letter) | |
{ | |
case 'M': return 1000; | |
case 'D': return 500; | |
case 'C': return 100; | |
case 'L': return 50; | |
case 'X': return 10; | |
case 'V': return 5; | |
case 'I': return 1; | |
default: | |
fprintf(stderr, "error: invalid Roman numeral letter '%c'\n", letter); | |
exit(1); | |
} | |
} | |
int intFromRoman(const char *s) | |
{ | |
int result = 0; | |
int lastValue = INT_MAX; | |
for (char ch = *s; ch != 0; ch = *(++s)) | |
{ | |
int value = romanLetterValue(ch); | |
if (value > lastValue) { | |
// We've seen something like "IX" or "XC". | |
// Need to undo the addition of the last value, | |
// and then add (value - lastValue). | |
result += (value - 2 * lastValue); | |
} | |
else { | |
result += value; | |
} | |
lastValue = value; | |
} | |
return result; | |
} | |
int main(int argc, const char **argv) | |
{ | |
for (int i = 1; i < argc; ++i) { | |
printf("%s = %d\n", argv[i], intFromRoman(argv[i])); | |
} | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment