-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.go
85 lines (77 loc) · 1.26 KB
/
converter.go
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
package roman_decimal
import (
"bytes"
"encoding/json"
"strings"
)
type RomanDecimalJSON interface {
ToJSON() ([]byte, error)
}
func (r *Roman) ToJSON() ([]byte, error) {
return json.Marshal(r)
}
func (d *Decimal) ToJSON() ([]byte, error) {
return json.Marshal(d)
}
var numToRomanMap = map[int]string{
1: "I",
4: "IV",
5: "V",
9: "IX",
10: "X",
40: "XL",
50: "L",
90: "XC",
100: "C",
400: "CD",
500: "D",
900: "CM",
1000: "M",
}
var romanToNumMap = map[string]int{
"I": 1,
"IV": 4,
"V": 5,
"IX": 9,
"X": 10,
"XL": 40,
"L": 50,
"XC": 90,
"C": 100,
"CD": 400,
"D": 500,
"CM": 900,
"M": 1000,
}
func (v *Roman) ToDecimal() int {
num := 0
for _, i := range v.pats {
if v, ok := romanToNumMap[i]; ok {
num += v
} else {
singleChars := strings.Split(i, "")
for _, s := range singleChars {
num += romanToNumMap[s]
}
}
}
v.Decimal = num
return num
}
func (d *Decimal) ToRoman() string {
var buffer bytes.Buffer
decimal := d.Num
nums := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
for decimal != 0 {
L1:
for _, i := range nums {
if (decimal - i) >= 0 {
buffer.WriteString(numToRomanMap[i])
decimal -= i
goto L1
}
}
}
d.Roman = buffer.String()
return d.Roman
}