Counter game

  • + 0 comments
    Basic Javascript Solution
    1. Find the next lower power of 2 less than N using while loop
    2. Compare with N to adjust N value and move to next turn
    3. Loop step 1, 2 until N is 1 and return the winner.
    function counterGame(n){
    	const player = ['Louise', 'Richard'];
    	let count = 0;
    	while ( n > 1 ){
    		let p = 0;
    		while ( 2**p < n){
    			p++;
    		}
    		if ( 2**p === n ) n/=2;
    		else n -=2**(p-1);
    		count++;
    	}
    	return player[(count+1)%2];
    }