779. K-th Symbol in Grammar

https://leetcode.com/problems/k-th-symbol-in-grammar/description/

class Solution {
public:
    int kthGrammar(int N, int K, bool rootZero = true) {
        if (N == 1)     return rootZero ? 0 : 1;
        int lastCnt = 1 << (N-2);
        if (K <= lastCnt) {
            return kthGrammar(N-1, K, rootZero);
        }
        else {
            return kthGrammar(N-1, K-lastCnt, !rootZero);
        }
    }
};

 

posted @ 2018-05-06 12:54  JTechRoad  阅读(89)  评论(0编辑  收藏  举报