Counter game

Sort by

recency

|

211 Discussions

|

  • + 0 comments

    C# solution with comments:

    public static string counterGame(long n)

        {
    
                bool currentPlayer1 = true;
    
    
        while(n > 1)
        {   
            // Check if n is a power of 2
            //A number is a power of 2 if it has exactly one 1 bit in its binary representation. (i.e. 100)         
            if((n & (n - 1)) == 0)
            {
                n = n/2;             
            }
            else
            {             
                //Math.Log(n, 2) -  Math.Log(20, 2) will return approximately 4.32 because 2 4.32 = 20
                //Math.Floor(4.32) round down, so will produce 4.
                //Math.Pow(2, 4) which will produce 16
                //So finally 20 - 16, will give 4, which will be the new number for the next turn.
                long largestPowerOf2 = (long)Math.Pow(2, (long)Math.Floor(Math.Log(n, 2)));
                n -= largestPowerOf2;                                
            }
    
            currentPlayer1 = !currentPlayer1;
    
        }
    
        return currentPlayer1 ? "Richard" : "Louise";
    }
    
  • + 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";
    }