forked from TonnyL/Windary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RomanToInteger.kt
executable file
·38 lines (33 loc) · 959 Bytes
/
RomanToInteger.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
/**
* Given a roman numeral, convert it to an integer.
* Input is guaranteed to be within the range from 1 to 3999.
*
* Accepted.
*/
class RomanToInteger {
fun romanToInt(s: String): Int {
val dict = mapOf(
Pair('I', 1),
Pair('V', 5),
Pair('X', 10),
Pair('L', 50),
Pair('C', 100),
Pair('D', 500),
Pair('M', 1000))
val chars = s.toCharArray()
var result = 0
var i = 0
while (i < chars.size) {
if (i + 1 < chars.size
&& (dict[chars[i + 1]]!! > dict[chars[i]]!!)
&& (chars[i] == 'I' || chars[i] == 'X' || chars[i] == 'C')) {
result += dict[chars[i + 1]]!! - dict[chars[i]]!!
i++
} else {
result += dict[chars[i]]!!
}
i++
}
return result
}
}