23 lines
581 B
Kotlin
23 lines
581 B
Kotlin
|
class Solution {
|
||
|
private data class State(val result: Long, val n: Long) {
|
||
|
fun update(
|
||
|
target: Long,
|
||
|
mask: Long,
|
||
|
): State =
|
||
|
when {
|
||
|
n > 0 && mask.and(target) == 0L -> State(result.or((n.and(1L)) * mask), n.shr(1))
|
||
|
else -> this
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fun minEnd(
|
||
|
n: Int,
|
||
|
x: Int,
|
||
|
): Long =
|
||
|
(0..Long.SIZE_BITS)
|
||
|
.map { 1L.shl(it) }
|
||
|
.fold(State(x.toLong(), n - 1L)) { s, mask ->
|
||
|
s.update(x.toLong(), mask)
|
||
|
}.result
|
||
|
}
|