Difference between these 2 codes?

Link to problem:https://www.hackerrank.com/challenges/counter-game
The first solution is mine which isn’t being accepted while the second one is the AC solution.What’s the difference between them!!!

This is my solution

#include<bits/stdc++.h>
using namespace std;
int main()

{

unsigned long long int n,temp=0,count=0,p_count=0,winner=1;

int t;

scanf("%d",&t);

while(t–)
{

winner=1;

scanf("%llu",&n);
while(n!=1)
{
	if((n&(n-1))==0)		// n is a power of 2
	{

		n/=2;
	}
	else
	{
		n=n-pow(2,floor(log2(n)));
		count++;
	}
winner=!winner;
}
if(winner)
	puts("Richard");
else
	puts("Louise");

}
return 0;
}

The correct solution

#include<bits/stdc++.h>

using namespace std;

int main()

{

int t;

scanf("%d",&t);

while(t--)

{

    unsigned long long n;

    scanf("%llu",&n);


    unsigned long long k ;

    int winner = 1; //1 - richard 0 - louise


    while(n!=1)

    {

        if( n && !(n&(n-1)))

            n/=2;

        else

        {

             k = pow(2,floor(log2(n)));

             n-=k;

        }

        if(winner)

            winner = 0;

        else

            winner = 1;

    }

    if(winner)

        printf("Richard\n");

    else

        printf("Louise\n");

}

return 0;

}

Algorithm is correct. There is a small typecasting issue. The “pow” function returns double. You need to typecast it to int.
The difference between the 2 codes is that he is storing the pow output in a variable first, where it is getting typecasted. You are not.

In the code below, if you submit this, you will get a wrong answer. However, if you uncomment the lines I have commented out, and comment the “else n = n - pow(2,floor(log2(n)));” line, you will get a correct answer.

#include<bits/stdc++.h>

using namespace std;

int main() {

int t;

scanf("%d",&t);

while(t--) {

    unsigned long long n, k;

    scanf("%llu",&n);

    int winner = 1; //1 - richard 0 - louise

    while (n!=1) {

        if(n && !(n&(n-1))) n/=2;

        else n = n - pow(2,floor(log2(n)));

        // else {

        //      k = pow(2,floor(log2(n)));

        //      n-=k;

        // }

        winner=!winner;

    }

    if(winner) printf("Richard\n");

    else printf("Louise\n");

}

return 0;

}

1 Like