forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroman_numeral.c
93 lines (83 loc) · 1.69 KB
/
roman_numeral.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void num2char(char **num, int bit, int n)
{
int i;
char low, mid, high;
char *p = *num;
switch (n) {
case 2:
low = 'C';
mid = 'D';
high = 'M';
break;
case 1:
low = 'X';
mid = 'L';
high = 'C';
break;
case 0:
low = 'I';
mid = 'V';
high = 'X';
break;
}
if (bit > 0) {
switch (bit) {
case 1:
case 2:
case 3:
for (i = 0; i < bit; i++) {
*p++ = low;
}
break;
case 4:
*p++ = low;
*p++ = mid;
break;
case 5:
*p++ = mid;
break;
case 6:
case 7:
case 8:
*p++ = mid;
for (i = 5; i < bit; i++) {
*p++ = low;
}
break;
case 9:
*p++ = low;
*p++ = high;
break;
}
}
*num = p;
}
static char roman_numeral[64] = { '\0' };
static char *intToRoman(int num)
{
int i;
char *p = &roman_numeral[0];
int thousand_bit = num / 1000;
int hundred_bit = (num % 1000) / 100;
int ten_bit = (num % 100) / 10;
int one_bit = num % 10;
if (thousand_bit > 0) {
if (thousand_bit < 4) {
for (i = 0; i < thousand_bit; i++) {
*p++ = 'M';
}
}
}
num2char(&p, hundred_bit, 2);
num2char(&p, ten_bit, 1);
num2char(&p, one_bit, 0);
*p = '\0';
return roman_numeral;
}
int main(int argc, char **argv) {
printf("%s\n", intToRoman(atoi(argv[1])));
return 0;
}