K-th Symbol in Grammar

medium math recursion bit-manipulation

Problem

Row 1 is '0'. Each subsequent row replaces 0 -> 01 and 1 -> 10. Return the K-th symbol (1-indexed) in row N.

InputN=4, K=5
Output1
Row 4 starts 0110100110010110; position 5 is 1.

def kthGrammar(N, K):
    return bin(K-1).count('1') & 1
function kthGrammar(N, K) {
  let n = K - 1, c = 0;
  while (n) { c += n & 1; n >>>= 1; }
  return c & 1;
}
int kthGrammar(int N, int K) {
    return Integer.bitCount(K-1) & 1;
}
int kthGrammar(int N, int K) {
    return __builtin_popcount(K-1) & 1;
}
Time: O(log K) Space: O(1)