Skip to content

Commit 1123fd7

Browse files
authored
Create 0779-k-th-symbol-in-grammar.kt
1 parent 9ce8a27 commit 1123fd7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

kotlin/0779-k-th-symbol-in-grammar.kt

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
}

0 commit comments

Comments
 (0)