On the first row, we write a
Given row
0
. 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
.Given row
N
and index K
, return the K
-th indexed symbol in row N
. (The values of K
are 1-indexed.) (1 indexed).Example:
Input: n=2,k=2
Output: 1
Approach
Java
public class KThSymbolInGrammar {public static void main(String[] args) {int n = 2, k = 2;System.out.println(kthGrammar(n, k));}static int kthGrammar(int N, int K) {if (N == 1 && K == 1)return 0;int mid = (int) (Math.pow(2, N - 1) / 2);if (K <= mid)return kthGrammar(N - 1, K);return kthGrammar(N - 1, K - mid) == 0 ? 1 : 0;}}
C++
#include <bits/stdc++.h>using namespace std;int kthGrammar(int N, int K){if(N==1&&K==1)return 0;int mid=pow(2,N-1)/2;if(K<=mid)return kthGrammar(N-1,K);return !kthGrammar(N-1,K-mid);}int main(){int n=2,k=2;cout<<kthGrammar(n,k);return 0;}
No comments:
Post a Comment