From 49e73d89e6646d8aaef555a6a33ffd706e5fbf4f Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 19 Oct 2024 11:36:12 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB1545.=20Find=20the=20Kth=20Bi?= =?UTF-8?q?t=20in=20Nth=20Binary=20String=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/ Signed-off-by: Matej Focko --- cs/find-kth-bit-in-nth-binary-string.cs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 cs/find-kth-bit-in-nth-binary-string.cs diff --git a/cs/find-kth-bit-in-nth-binary-string.cs b/cs/find-kth-bit-in-nth-binary-string.cs new file mode 100644 index 0000000..0e24100 --- /dev/null +++ b/cs/find-kth-bit-in-nth-binary-string.cs @@ -0,0 +1,23 @@ +public class Solution { + public char FindKthBit(int n, int k) { + static char GetBit(int inversions) + => inversions % 2 == 0 ? '1' : '0'; + + var length = (1 << n) - 1; + + int inversions; + for (inversions = 0; k > 1; length >>= 1) { + // check for middle + if (k - 1 == length >> 1) { + return GetBit(inversions); + } + + if (k > length >> 1) { + k = length + 1 - k; + ++inversions; + } + } + + return GetBit(++inversions); + } +}