#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int winner(char s, int n)
{
int a=0,b=0;
int c=0;
while(c!=strlen(s))
{
if(c%2==0)
{
if(s[c]==‘1’)
a++;
if(b>((2 n)-c)/2 -1)
break;
}
else
{
if(s[c]==‘1’)
b++;
if(a>((2*n)-(c-1))/2 -1)
break;
}
c++;
}
if(s[c]=='\0')
return c;
return c+1;
}
int main()
{
int t,n;
char *s;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
scanf("%d",&n);
s=(char )malloc(2 n * sizeof(char));
scanf("%s",s);
printf("%d\n",winner(s,n));
free(s);
}
return 0;
}
This code is running perfectly on my local pc. Don’t really understand why it is showing a runtime error in here
Format your code.
Use ``` at the start and end of code
Send the question link
So that your code is easy to read
This is the question link
I did not get you! Are you suggesting me to add comments?
ssjgz
May 13, 2020, 7:34pm
9
Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int winner(char *s, int n)
{
int a=0,b=0;
int c=0;
while(c!=strlen(s))
{
if(c%2==0)
{
if(s[c]=='1')
a++;
if(b>((2*n)-c)/2 -1)
break;
}
else
{
if(s[c]=='1')
b++;
if(a>((2*n)-(c-1))/2 -1)
break;
}
c++;
}
if(s[c]=='\0')
return c;
return c+1;
}
int main()
{
int t,n;
char *s;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
scanf("%d",&n);
s=(char *)malloc(2*n * sizeof(char));
scanf("%s",s);
printf("%d\n",winner(s,n));
free(s);
}
return 0;
}
1 Like
ssjgz
May 13, 2020, 7:49pm
14
The problem that immediately jumps out is that you aren’t allocating enough memory for s
: it must contain all 2 * n
characters it reads in, plus the null-terminator character.
3 Likes
Yeah you always need to allocate size+1. But I would suggest to use string