779. K-th Symbol in Grammar
class Solution { public: int kthGrammar(int N, int K) { return helper(N, K, false); } int helper(int n, int k, bool reverse) { if (n == 1) return reverse; int total = 1 << (n-1); int half = total >> 1; if (k <= half) return helper(n-1, k, reverse); else return helper(n-1, k-half, !reverse); } }; /* lvl1: 0 lvl2: 0 1 lvl3: 0 1 1 0 lvl4: 0 1 1 0 1 0 0 1 lvl5: 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 */