Skip to content

Commit 3ab8518

Browse files
Roman to integer
Signed-off-by: begeekmyfriend <[email protected]>
1 parent b1393ac commit 3ab8518

File tree

4 files changed

+52
-0
lines changed

4 files changed

+52
-0
lines changed
File renamed without changes.
File renamed without changes.

013_roman_to_integer/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test roman_to_integer.c
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
static int roman_to_integer(char c)
5+
{
6+
switch(c) {
7+
case 'I':
8+
return 1;
9+
case 'V':
10+
return 5;
11+
case 'X':
12+
return 10;
13+
case 'L':
14+
return 50;
15+
case 'C':
16+
return 100;
17+
case 'D':
18+
return 500;
19+
case 'M':
20+
return 1000;
21+
default:
22+
return;
23+
}
24+
}
25+
26+
int romanToInt (char *s) {
27+
int i, result = roman_to_integer(s[0]);
28+
29+
for (i = 1; s[i] != '\0'; i++) {
30+
int prev = roman_to_integer(s[i - 1]);
31+
int curr = roman_to_integer(s[i]);
32+
//if left<right such as : IV(4), XL(40), IX(9) ...
33+
if (prev < curr) {
34+
result = result - prev + (curr - prev);
35+
} else {
36+
result += curr;
37+
}
38+
}
39+
40+
return result;
41+
}
42+
int main(int argc, char **argv)
43+
{
44+
if (argc < 2) {
45+
fprintf(stderr, "Usage: ./test roman\n");
46+
exit(-1);
47+
}
48+
printf("%d\n", romanToInt(argv[1]));
49+
return 0;
50+
}

0 commit comments

Comments
 (0)