Counter game

  • + 0 comments

    c++ solution i prepare an array that stores consecutive values of power of 2. then i do simulation of the game and checking if the current 'n' is power of 2 which in binary has only 1 bit set, hence i use built-in function to count bits that are 1 in a number. I also keep track of who would win at the moment in 'louise' variable

    string counterGame(long n) {
        const int l = 63;
        vector<long> pows(l);
        for (long i = 0; i < l; i++) {
            pows[i] = (1l<<i);
        }
        
        bool louise = false;
        
        while (n > 1) {
            louise ^= 1;
            
            auto lb = lower_bound(pows.begin(),pows.end(),n);
            int indx = distance(pows.begin(), lb);
            
            if (__builtin_popcount(n)==1) {
                n >>= 1l;
            } else {
                n -= pows[indx-1];
            }
        }
        
        return louise ? "Louise" : "Richard";
    }