Find Kth Bit in Nth Binary String

Medium Recursion AI round

A sequence of binary strings is made round by round. The first string, S1, is "0". Each string after it is made from the one before: write the previous string, then a single "1", then the previous string again with every bit flipped (each 0 becomes a 1, and each 1 a 0) and read from the last character to the first.

Given n and k, look at the string Sn, and find its k-th character, counting from 1.

Return that character as a string of one character, "0" or "1".

Example 1

Input: n = 3, k = 5
Output: "0"

S1 is "0". S2 is "0", then "1", then "0" flipped and reversed, "1": "011". S3 is "011", then "1", then "011" flipped, "100", and reversed, "001": "0111001", and its 5th character is 0.

Example 2

Input: n = 5, k = 27
Output: "1"

S4 is 011100110110001. S5 is S4, then a 1, then S4 flipped, 100011001001110, and read backwards, 011100100110001: 0111001101100011011100100110001. Its 27th character is 1.

Example 3

Input: n = 6, k = 40
Output: "1"

Constraints

  • 1 ≤ n ≤ 31
  • 1 ≤ k ≤ 2ⁿ - 1, the length of Sn, so k never passes 2³¹ - 1 and fits in a signed 32-bit integer

More Recursion

All Recursion problems