-
Notifications
You must be signed in to change notification settings - Fork 0
/
NextBiggerNumberWithTheSameDigits.kt
58 lines (50 loc) · 1.57 KB
/
NextBiggerNumberWithTheSameDigits.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
package com.smlnskgmail.jaman.codewarskotlin.kyu4
class NextBiggerNumberWithTheSameDigits(
private val input: Long
) {
@Suppress("ComplexMethod", "ReturnCount")
fun solution(): Long {
val splittedInput = input.toString()
.split("")
.filter { s -> s.isNotEmpty() }
var pivot = -1
for (i in splittedInput.size - 1 downTo 0) {
val nextIndex = i - 1
if (nextIndex >= 0 && splittedInput[i] > splittedInput[nextIndex]) {
pivot = nextIndex
break
}
}
if (pivot == -1) {
return -1
}
val rightSide = ArrayList(splittedInput.subList(pivot, splittedInput.size))
val extractedPivot = rightSide.removeAt(0)
var minimum: String? = null
var minimumIndex = -1
rightSide.indices.forEach {
if (rightSide[it] > extractedPivot) {
val number = rightSide[it]
if (minimum == null || number < minimum!!) {
minimum = number
minimumIndex = it
}
}
}
if (minimumIndex == -1) {
return -1
}
rightSide.removeAt(minimumIndex)
rightSide.add(extractedPivot)
rightSide.sort()
val result = "${
splittedInput.subList(0, pivot)
.joinToString("")
}$minimum${rightSide.joinToString("")}"
.toLong()
if (result < input) {
return -1
}
return result
}
}