File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ fun kthGrammar (n : Int , k : Int ): Int {
3
+ var cur = 0
4
+ var left = 1
5
+ var right = 2.0 .pow(n - 1 ).toInt()
6
+
7
+ repeat (n - 1 ) {
8
+ val mid = (left + right) / 2
9
+ if (k <= mid) {
10
+ right = mid
11
+ } else {
12
+ left = mid + 1
13
+ cur = if (cur == 1 ) 0 else 1
14
+ }
15
+ }
16
+
17
+ return cur
18
+ }
19
+ }
20
+
21
+ // another solution using the same thought but different way of coding it
22
+ class Solution {
23
+ fun kthGrammar (n : Int , k : Int ): Int {
24
+ if (n == 1 ) return 0
25
+ if (k % 2 == 0 ) return if (kthGrammar(n - 1 , k / 2 ) == 0 ) 1 else 0
26
+ else return if (kthGrammar(n - 1 , (k + 1 ) / 2 ) == 0 ) 0 else 1
27
+ }
28
+ }
29
+
30
+ // another solution, recommend reading https://leetcode.com/problems/k-th-symbol-in-grammar/solutions/113705/java-one-line/ for explanation
31
+ class Solution {
32
+ fun kthGrammar (n : Int , k : Int ) = Integer .bitCount(k - 1 ) and 1
33
+ }
You can’t perform that action at this time.
0 commit comments