-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroman.c
102 lines (83 loc) · 1.79 KB
/
roman.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
94
95
96
97
98
99
100
101
102
// Licensed under the MIT License.
#include <stdint.h>
#include <string.h>
#include "roman.h"
#define KEYS 13
static String romans[KEYS] =
{
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
};
static int values[KEYS] =
{
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
};
int roman_from_char(char value)
{
switch (value)
{
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: return 0;
}
}
int roman_from_string_builder(StringBuilder value)
{
if (value->length == 0)
{
return 0;
}
int result = 0;
int previous = 0;
int subtractive = false;
for (size_t i = value->length - 1; i != SIZE_MAX; i--)
{
int current = roman_from_char(value->buffer[i]);
subtractive = current < previous;
previous = current;
if (subtractive)
{
result -= current;
}
else
{
result += current;
}
}
return result;
}
size_t roman_length(int value)
{
size_t result = 0;
for (int i = 0; i < KEYS; i++)
{
result += (value / values[i]) * strlen(romans[i]);
value %= values[i];
}
return result;
}
Exception roman_to_string_builder(StringBuilder result, int value)
{
Exception ex = string_builder(result, 0);
if (ex)
{
return ex;
}
for (int i = 0; i < KEYS; i++)
{
while (value / values[i])
{
ex = string_builder_append_string(result, romans[i]);
if (ex)
{
return ex;
}
value -= values[i];
}
}
return 0;
}