Skip to content

Commit 8a56aa4

Browse files
committed
solved: 779
1 parent 07464ca commit 8a56aa4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

code/779.k-th-symbol-in-grammar.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// @leet start
2+
3+
/**
4+
* compare to row4 & row5
5+
*
6+
* row4 : 01101001
7+
* row5 : 011010011001011
8+
*
9+
* so we can see that row5 is row4 + row4's reverse
10+
*
11+
* row5 : row4 + reverse(row4)
12+
* -> recursion!!!!
13+
*
14+
* if k <= mid: the nth in row-n is the same as the kth in row-(n-1)
15+
* if k > mid: the nth in row-n is the opposite of the kth in row-(n-1)
16+
*/
17+
function kthGrammar(n: number, k: number): number {
18+
if (n === 1) {
19+
return 0;
20+
}
21+
22+
const mid = 2 ** (n - 1) / 2;
23+
24+
if (k <= mid) {
25+
return kthGrammar(n - 1, k);
26+
} else {
27+
return 1 - kthGrammar(n - 1, k - mid);
28+
}
29+
}
30+
// @leet end
31+

0 commit comments

Comments
 (0)