简单题,用一个数组存储从i到n共有多少个1,方便移位的时候计数
只有以下三种情况:
1、l=n如果满足条件,直接输出,否则需要修改1
2、l=n+1需要删除1或0
3、l=n-1需要添加1或0
这个题输入的时候要用scanf或cin(题目提示有空格或空行)
#include <stdio.h>
#include <string.h>
char s[1050];
int d[1050],cnt;
int main()
{
int n;
scanf("%d",&n);
while(scanf("%s",s+1)==1)
{
int l=strlen(s+1);
d[l+1]=0;
cnt=0;
for(int i=l;i>=1;i--)
{
d[i]=d[i+1];
if(s[i]=='1')
{
d[i]++;
cnt+=i;
}
}
if(l==n)
{
if(cnt%(n+1)==0)puts(s+1);
else
{
for(int i=1;i<=l;i++)
{
if(s[i]=='1'&&((cnt-i)%(n+1)==0))
{
s[i]='0';
puts(s+1);break;
}
}
}
}
if(l-1==n)
{
for(int i=1;i<=l;i++)
{
if(s[i]=='1'&&((cnt-i-d[i+1])%(n+1)==0))
{
for(int j=1;j<=l;j++)
{
if(j!=i)printf("%c",s[j]);
}printf("\n");
break;
}
if(s[i]=='0'&&((cnt-d[i+1])%(n+1)==0))
{
for(int j=1;j<=l;j++)
{
if(j!=i)printf("%c",s[j]);
}printf("\n");
break;
}
}
}
if(l+1==n)
{
for(int i=1;i<=l+1;i++)
{
if((cnt+d[i])%(n+1)==0)
{
for(int j=1;j<i;j++)
{
printf("%c",s[j]);
}
printf("0");
for(int j=i;j<=l;j++)
{
printf("%c",s[j]);
}
printf("\n");
break;
}
if((cnt+i+d[i])%(n+1)==0)
{
for(int j=1;j<i;j++)
{
printf("%c",s[j]);
}
printf("1");
for(int j=i;j<=l;j++)
{
printf("%c",s[j]);
}
printf("\n");
break;
}
}
}
}
return 0;
}