cs: add «1545. Find the Kth Bit in Nth Binary String»
URL: https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
94390bbf94
commit
49e73d89e6
1 changed files with 23 additions and 0 deletions
23
cs/find-kth-bit-in-nth-binary-string.cs
Normal file
23
cs/find-kth-bit-in-nth-binary-string.cs
Normal file
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue