-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntegerToRoman.kt
130 lines (110 loc) · 3.34 KB
/
IntegerToRoman.kt
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package problems
import java.util.*
import kotlin.collections.ArrayList
object IntegerToRoman {
//Think of a method to implement this with Reverse a LinkedList
//Think of the modulus way...modulus to get the first digit (MSB)
data class RomanNumeral (
val precedent: Char?,
val value: Int
)
data class RomanString (
val ones: Char,
val fives: Char,
val tens: Char
)
//Clean method
fun intToRomanNoList(num: Int): String {
val romanKey = ArrayList<RomanString>()
romanKey.add(RomanString('I', 'V', 'X'))
romanKey.add(RomanString('X', 'L', 'C'))
romanKey.add(RomanString('C', 'D', 'M'))
romanKey.add(RomanString('M', '!', '?'))
var input = num
var currentDigit = 0
var romanNumber = ""
while (input != 0) {
val digit = input % 10
val key = romanKey[currentDigit]
var tempString = ""
when {
digit == 4 -> {
tempString = "${key.ones}${key.fives}"
}
digit == 9 -> {
tempString ="${key.ones}${key.tens}"
}
digit >= 5 -> {
var tempDigit = digit
tempDigit -= 5
tempString = "${key.fives}"
for (i in 1..tempDigit) {
tempString += key.ones
}
}
else -> {
for (i in 1..digit) {
tempString += key.ones
}
}
}
romanNumber = tempString + romanNumber
input /= 10
currentDigit++
}
return romanNumber
}
//old method
fun intToRomanWithList(num: Int): String {
val romanKey = ArrayList<RomanString>()
romanKey.add(RomanString('I', 'V', 'X'))
romanKey.add(RomanString('X', 'L', 'C'))
romanKey.add(RomanString('C', 'D', 'M'))
romanKey.add(RomanString('M', '!', '?'))
var input = num
val digitList = LinkedList<Int>()
var romanNumber = ""
while (input != 0) {
digitList.add(input % 10)
input /= 10
}
digitList.forEachIndexed { index, digit ->
/*
1 I
2 II
3 III
4 IV
5 V
6 VI
7 VII
8 VII
9 IX
*/
val key = romanKey[index]
var tempString = ""
when {
digit == 4 -> {
tempString = "${key.ones}${key.fives}"
}
digit == 9 -> {
tempString ="${key.ones}${key.tens}"
}
digit >= 5 -> {
var tempDigit = digit
tempDigit -= 5
tempString = "${key.fives}"
for (i in 1..tempDigit) {
tempString += key.ones
}
}
else -> {
for (i in 1..digit) {
tempString += key.ones
}
}
}
romanNumber = tempString + romanNumber
}
return romanNumber
}
}