We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
{
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";
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Counter game
You are viewing a single comment's thread. Return to all comments →
C# solution with comments:
public static string counterGame(long n)