Skip to content

Commit 9418aea

Browse files
authored
Added task 779.
1 parent 70d2315 commit 9418aea

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package g0701_0800.s0779_k_th_symbol_in_grammar;
2+
3+
// #Medium #Math #Bit_Manipulation #Recursion
4+
5+
@SuppressWarnings("java:S1172")
6+
public class Solution {
7+
/*
8+
* Time: O(logn)
9+
* Space: O(1)
10+
*/
11+
public int kthGrammar(int n, int k) {
12+
return Integer.bitCount(k - 1) % 2;
13+
}
14+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
779\. K-th Symbol in Grammar
2+
3+
Medium
4+
5+
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the <code>1<sup>st</sup></code> 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`.
6+
7+
* For example, for `n = 3`, the <code>1<sup>st</sup></code> row is `0`, the <code>2<sup>nd</sup></code> row is `01`, and the <code>3<sup>rd</sup></code> row is `0110`.
8+
9+
Given two integer `n` and `k`, return the <code>k<sup>th</sup></code> (**1-indexed**) symbol in the <code>n<sup>th</sup></code> row of a table of `n` rows.
10+
11+
**Example 1:**
12+
13+
**Input:** n = 1, k = 1
14+
15+
**Output:** 0
16+
17+
**Explanation:** row 1: 0
18+
19+
**Example 2:**
20+
21+
**Input:** n = 2, k = 1
22+
23+
**Output:** 0
24+
25+
**Explanation:** row 1: 0 row 2: 01
26+
27+
**Example 3:**
28+
29+
**Input:** n = 2, k = 2
30+
31+
**Output:** 1
32+
33+
**Explanation:** row 1: 0 row 2: 01
34+
35+
**Constraints:**
36+
37+
* `1 <= n <= 30`
38+
* <code>1 <= k <= 2<sup>n - 1</sup></code>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g0701_0800.s0779_k_th_symbol_in_grammar;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void kthGrammar() {
11+
assertThat(new Solution().kthGrammar(1, 1), equalTo(0));
12+
}
13+
14+
@Test
15+
void kthGrammar2() {
16+
assertThat(new Solution().kthGrammar(2, 1), equalTo(0));
17+
}
18+
19+
@Test
20+
void kthGrammar3() {
21+
assertThat(new Solution().kthGrammar(2, 2), equalTo(1));
22+
}
23+
}

0 commit comments

Comments
 (0)