kt: add «3133. Minimum Array End»

URL:	https://leetcode.com/problems/minimum-array-end/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-11-09 23:17:59 +01:00
parent 437712377a
commit b6b91b1055
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

22
kt/minimum-array-end.kt Normal file
View file

@ -0,0 +1,22 @@
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
}