簡單題,用一個數組存儲從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;
}