Counter game

Sort by

recency

|

210 Discussions

|

  • + 0 comments
    def counterGame(n):
        # Write your code here
        turns = 0
        while n > 1:
            if(n&(n-1) == 0):
                n//=2
            else:
                highest_power_of_2 = 1
                while highest_power_of_2*2<=n:
                    highest_power_of_2*=2
                n-=highest_power_of_2
            turns += 1
        if turns %2 == 0:
            return "Richard"
        else:
            return "Louise"
    
  • + 0 comments

    Javascript

    function counterGame(n) {
        // Write your code here    
        var turn = 0
        while(n > 1){
            n = Math.log2(n) % 1 == 0 ? n/2 : n - Math.pow(2, Math.floor(Math.log2(n)))        
            turn ++
        }
        return turn % 2 == 0 ? 'Richard' : 'Louise'
    }
    
  • + 0 comments

    Java solution class Result {

    public static String counterGame(long n) {
        if (n == 1) return "Richard";
    
        int turn = 0;
        while (n > 1) {
            if ((n & (n - 1)) == 0) { // Check if n is a power of two
                n /= 2;
            } else {
                n -= Long.highestOneBit(n); // Get the largest power of 2 less than or equal to n
            }
            turn++;
        }
        return (turn % 2 == 0) ? "Richard" : "Louise";
    }
    

    }

  • + 0 comments

    Javascript

    function counterGame(n) {
        let turn = 0;
        let log = Math.log2(n);
        while (log % 1 !== 0) {
            n -= Math.pow(2, Math.floor(log)); //subtract nearest power of 2
            turn++;
            log = Math.log2(n);
        }
        const endTurn = turn + log;
        return endTurn % 2 === 0 ? "Richard" : "Louise";
    }
    
  • + 0 comments

    c++

    string counterGame(long n) {
    
     std::bitset<sizeof(long) * 8> bits = n-1;
     
     if(bits.count() % 2 == 0){
        return "Richard";
     }
     return "Louise";
    }