【lc刷题】1545. Find Kth Bit in Nth Binary String

题目:

Given two positive integers n and k, the binary string Sn is formed as follows:

S1 = “0”
Si = Si-1 + “1” + reverse(invert(Si-1)) for i > 1
Where + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).

For example, the first 4 strings in the above sequence are:

S1 = “0”
S2 = “011”
S3 = “0111001”
S4 = “011100110110001”
Return the kth bit in Sn. It is guaranteed that k is valid for the given n.

Example 1:

Input: n = 3, k = 1
Output: “0”
Explanation: S3 is “0111001”. The first bit is “0”.
Example 2:

Input: n = 4, k = 11
Output: “1”
Explanation: S4 is “011100110110001”. The 11th bit is “1”.

Example 3:
Input: n = 1, k = 1
Output: “0”

Example 4:
Input: n = 2, k = 3
Output: “1”

Constraints:
1 <= n <= 20
1 <= k <= 2n - 1
来源

思路:dfs

S1 = “0”
S2 = “0 1 1”
S3 = “011 1 001”
S4 = “0111001 1 0110001”
k如果是1,那么返回肯定是0
如果是2,返回肯定是1
如果是中间数,肯定是1
只要是前半段的,返回的都是固定的,如果是后半段,我们只需要找对应的前半段的数。

譬如,对于S4 (n=4),k=11,则length=15,mid=8,那么11对应的前半段数就是 8-(11-8) = 5
我们拿着k=5去S3(n=3)找,则length=7,mid=4,那么5对应的前半段数就是 4-(5-4) = 3
我们拿着k=3去S2(n=2)找,则length=3,mid=2,那么3对应的前半段数就是 2-(3-2) = 1
这时k=1,返回0,
拿着这个0再往回倒饬,S2那里就是1,S3那里就是0,S4那里就是1
所以结果是1.

其实,这道题用暴力解,python算出所有排序然后切片的那个值也能过。

class Solution:
    def findKthBit(self, n: int, k: int) -> str:       
        len_list = [0]*(n+1)
        len_list[1] = 1
        for i in range(1, n+1):
            len_list[i] = 2*len_list[i-1] + 1
        # 打表出来,首个空着,因为是从1开始算 [0, 1, 3, 7, 15, 31, ...]
        
        def dfs(n, k):
            mid = len_list[n-1] + 1
            if k == 1: return 0 
            elif k == 2: return 1
            elif k < mid: # if k in the first half, go up
                return dfs(n-1, k)
            elif k == mid: # if k equals mid, return 1
                return 1
            else: # if k in the second half, go up and k equals its counterpart
                return 1 - dfs(n-1, mid-(k-mid))
        return str(dfs(n, k))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值