Day 25
第K个语法符号
Date: October 20, 2022 10:57 AM
https://leetcode.cn/problems/k-th-symbol-in-grammar/description/
找规律
1: 0
2: 0 1
3: 0 1 1 0
4: 0 1 1 0 1 0 0 1
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n==1:# 递归到第一行
return 0
if k <= (1 << n-2): # 如果在前半段,与上一行的相等,即还是第k个数
return self.kthGrammar(n-1, k)
else:# 如果在后半段,与上一行在第k-2^n-2的异或相等
return self.kthGrammar(n-1, k - (1 << n-2)) ^ 1