返回介绍

solution / 0700-0799 / 0779.K-th Symbol in Grammar / README_EN

发布于 2024-06-17 01:03:34 字数 3721 浏览 0 评论 0 收藏 0

779. K-th Symbol in Grammar

中文文档

Description

We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

  • For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.

Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.

 

Example 1:

Input: n = 1, k = 1
Output: 0
Explanation: row 1: 0

Example 2:

Input: n = 2, k = 1
Output: 0
Explanation: 
row 1: 0
row 2: 01

Example 3:

Input: n = 2, k = 2
Output: 1
Explanation: 
row 1: 0
row 2: 01

 

Constraints:

  • 1 <= n <= 30
  • 1 <= k <= 2n - 1

Solutions

Solution 1

class Solution:
  def kthGrammar(self, n: int, k: int) -> int:
    if n == 1:
      return 0
    if k <= (1 << (n - 2)):
      return self.kthGrammar(n - 1, k)
    return self.kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1
class Solution {
  public int kthGrammar(int n, int k) {
    if (n == 1) {
      return 0;
    }
    if (k <= (1 << (n - 2))) {
      return kthGrammar(n - 1, k);
    }
    return kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1;
  }
}
class Solution {
public:
  int kthGrammar(int n, int k) {
    if (n == 1) return 0;
    if (k <= (1 << (n - 2))) return kthGrammar(n - 1, k);
    return kthGrammar(n - 1, k - (1 << (n - 2))) ^ 1;
  }
};
func kthGrammar(n int, k int) int {
  if n == 1 {
    return 0
  }
  if k <= (1 << (n - 2)) {
    return kthGrammar(n-1, k)
  }
  return kthGrammar(n-1, k-(1<<(n-2))) ^ 1
}

Solution 2

class Solution:
  def kthGrammar(self, n: int, k: int) -> int:
    return (k - 1).bit_count() & 1
class Solution {
  public int kthGrammar(int n, int k) {
    return Integer.bitCount(k - 1) & 1;
  }
}
class Solution {
public:
  int kthGrammar(int n, int k) {
    return __builtin_popcount(k - 1) & 1;
  }
};
func kthGrammar(n int, k int) int {
  return bits.OnesCount(uint(k-1)) & 1
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文