From b6b91b10554126373b83935cb4b4b2d0688e0662 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 9 Nov 2024 23:17:59 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB3133.=20Minimum=20Array=20End?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/minimum-array-end/ Signed-off-by: Matej Focko --- kt/minimum-array-end.kt | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 kt/minimum-array-end.kt diff --git a/kt/minimum-array-end.kt b/kt/minimum-array-end.kt new file mode 100644 index 0000000..bcad6a8 --- /dev/null +++ b/kt/minimum-array-end.kt @@ -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 +}