Matej Focko
b6b91b1055
URL: https://leetcode.com/problems/minimum-array-end/ Signed-off-by: Matej Focko <me@mfocko.xyz>
22 lines
581 B
Kotlin
22 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
|
|
}
|