Skip to content

Commit c7ff69a

Browse files
add problem 13 and test function
1 parent 60af10a commit c7ff69a

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

C/1-50/13-Roman-to-Integer.c

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* Given a roman numeral, convert it to an integer.
3+
4+
* Input is guaranteed to be within the range from 1 to 3999.
5+
* Created by supercoderx on 2017/8/11.
6+
*/
7+
#include
8+
9+
int romanToInt(char *s) {
10+
char chs[] = "IVXLCDM";
11+
int chsNum[] = {1, 5, 10, 50, 100, 500, 1000}, len = 0, chsLen = 7, id, prevId, res = 0;
12+
13+
char *ch = s;
14+
while (*ch != '\0') {
15+
ch++;
16+
len++;
17+
}
18+
19+
for (int i = len - 1; i >= 0; i--) {
20+
for (int j = 0; j < chsLen; j++)
21+
if (s[i] == chs[j]) {
22+
id = j;
23+
break;
24+
}
25+
if (i == len - 1) {
26+
res = chsNum[id];
27+
prevId = id;
28+
} else {
29+
if (chsNum[id] < chsNum[prevId])
30+
res -= chsNum[id];
31+
else
32+
res += chsNum[id];
33+
prevId = id;
34+
}
35+
}
36+
37+
return res;
38+
}
39+
40+
void testRomanToInt() {
41+
char *s1 = "IV";
42+
printf("%d", romanToInt(s1));
43+
}

0 commit comments

Comments
 (0)