Skip to content

Commit b89df0c

Browse files
committed
Added task 13.
1 parent 2570ea4 commit b89df0c

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package g0001_0100.s0013_roman_to_integer
2+
3+
class Solution {
4+
fun romanToInt(s: String): Int {
5+
var x = 0
6+
var y: Char
7+
for (i in s.indices) {
8+
y = s[i]
9+
when (y) {
10+
'I' -> x = getX(s, x, i, 1, 'V', 'X')
11+
'V' -> x += 5
12+
'X' -> x = getX(s, x, i, 10, 'L', 'C')
13+
'L' -> x += 50
14+
'C' -> x = getX(s, x, i, 100, 'D', 'M')
15+
'D' -> x += 500
16+
'M' -> x += 1000
17+
else -> {}
18+
}
19+
}
20+
return x
21+
}
22+
23+
private fun getX(s: String, x: Int, i: Int, i2: Int, v: Char, x2: Char): Int {
24+
var localX = x
25+
if (i + 1 == s.length) {
26+
localX += i2
27+
} else if (s[i + 1] == v) {
28+
localX -= i2
29+
} else if (s[i + 1] == x2) {
30+
localX -= i2
31+
} else {
32+
localX += i2
33+
}
34+
return localX
35+
}
36+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package g0001_0100.s0013_roman_to_integer
2+
3+
import org.hamcrest.CoreMatchers.equalTo
4+
import org.hamcrest.MatcherAssert.assertThat
5+
6+
import org.junit.Test
7+
8+
class SolutionTest {
9+
@Test
10+
fun romanToInt() {
11+
val solution = Solution()
12+
assertThat(solution.romanToInt("III"), equalTo(3))
13+
assertThat(solution.romanToInt("IV"), equalTo(4))
14+
assertThat(solution.romanToInt("IX"), equalTo(9))
15+
assertThat(solution.romanToInt("LVIII"), equalTo(58))
16+
assertThat(solution.romanToInt("MCMXCIV"), equalTo(1994))
17+
}
18+
19+
}

0 commit comments

Comments
 (0)