-
Notifications
You must be signed in to change notification settings - Fork 0
/
RomanInteger.kt
55 lines (54 loc) · 1.5 KB
/
RomanInteger.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
class Solution {
fun romanToInt(s: String): Int {
val specialCases=hashMapOf<String,Int>(
"IV" to 4,
"CM" to 900,
"XC" to 90,
"IX" to 9,
"XL" to 40,
"CD" to 400
)
val map=hashMapOf<String,Int>(
"I" to 1,
"V" to 5,
"X" to 10,
"L" to 50,
"C" to 100,
"D" to 500,
"M" to 1000
)
var sum=0
var i=0
while(i<s.length){
val current=s[i].toString()
when(current){
"I",
"X",
"C"->{
if(i<s.length-1){
val next=s[i+1].toString()
if(specialCases.containsKey(current+next)){
sum+=specialCases[current+next]!!
s.replace(current+next,"")
i+=2
}else{
sum+=map[current]!!
s.replace(current,"")
i++
}
}else{
sum+=map[current]!!
s.replace(current,"")
i++
}
}
else->{
i++
sum+=map[current]!!
s.replace(current,"")
}
}
}
return sum
}
}