Skip to content

Commit 9ce8a27

Browse files
Update 0779-k-th-symbol-in-grammar.java
1 parent f3a508f commit 9ce8a27

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

java/0779-k-th-symbol-in-grammar.java

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
1-
//Explanation: https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2174956/Easy-java-solution-or-Imagine-a-binary-tree. (Upvote if you liked!!)
2-
//Asked in: Google (lintcode)
3-
41
class Solution {
5-
62
public int kthGrammar(int n, int k) {
7-
if (n == 1 || k == 1) return 0;
8-
int prevK = (int) Math.pow(2, n - 2);
9-
if (k <= prevK) return kthGrammar(n - 1, k); else {
10-
int presK = k % prevK;
11-
int val = kthGrammar(n - 1, presK == 0 ? k / 2 : k % prevK);
12-
return val == 1 ? 0 : 1;
3+
int left = 1;
4+
int right = (int)Math.pow(2,n-1);
5+
int cur = 0;
6+
7+
for(int i = 0; i < n-1; i++){
8+
int mid = (left + right)/2;
9+
if(k <= mid)
10+
right = mid;
11+
else{
12+
left = mid + 1;
13+
cur = (cur == 1)? 0: 1;
14+
}
1315
}
16+
return cur;
1417
}
1518
}

0 commit comments

Comments
 (0)