1545. Find Kth Bit in Nth Binary String #723
-
Topics: Given two positive integers
Where For example, the first four strings in the above sequence are:
Return the Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to understand the recursive process used to generate each binary string Approach:
Let's implement this solution in PHP: 1545. Find Kth Bit in Nth Binary String <?php
/**
* @param Integer $n
* @param Integer $k
* @return String
*/
function findKthBit($n, $k) {
if ($n == 1) {
return "0";
}
$mid = (1 << ($n - 1)); // 2^(n-1)
if ($k == $mid) {
return "1";
} elseif ($k < $mid) {
return findKthBit($n - 1, $k);
} else {
$result = findKthBit($n - 1, $mid * 2 - $k);
return $result === "0" ? "1" : "0"; // Flip the bit
}
}
?> Explanation:
Complexity Analysis:
Example Walkthrough:
By leveraging recursion and properties of the string construction, this solution avoids generating the entire string, making it efficient even for larger n. |
Beta Was this translation helpful? Give feedback.
We need to understand the recursive process used to generate each binary string
Sn
and use this to determine thek
-th bit without constructing the entire string.Approach:
Recursive String Construction:
i > 1
:Si
is constructed as:Si = Si-1 + "1" + reverse(invert(Si-1))
Key Observations: