- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinteger_to_roman.go
46 lines (40 loc) · 1.09 KB
/
integer_to_roman.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
package main
import"strings"
typetuplestruct {
charstring
valint
}
funcintToRoman(numint) string {
//Step1: Store roman characters along with the corresponding value in decreasing order of the integer value
slice:=make([]tuple, 13)
slice[0] =tuple{"M", 1000}
slice[1] =tuple{"CM", 900}
slice[2] =tuple{"D", 500}
slice[3] =tuple{"CD", 400}
slice[4] =tuple{"C", 100}
slice[5] =tuple{"XC", 90}
slice[6] =tuple{"L", 50}
slice[7] =tuple{"XL", 40}
slice[8] =tuple{"X", 10}
slice[9] =tuple{"IX", 9}
slice[10] =tuple{"V", 5}
slice[11] =tuple{"IV", 4}
slice[12] =tuple{"I", 1}
varres strings.Builder
//Step2: Loop through the slice, and divide the number to get the count.
//Repeat the corresponding roman character by count in the result string.
//Take the remainder and repeat the loop
fori:=0; i<13; i++ {
count:=num/slice[i].val
ifcount>0 {
str:=strings.Repeat(slice[i].char, count)
res.WriteString(str)
}
num=num%slice[i].val
//Optimization: once num becomes 0, break out of the loop
ifnum==0 {
break
}
}
returnres.String()
}