题意:输入为一个ISBN号码,其中有一位空缺,用?表示。求空缺位应该填入的数字,如果?处填入什么都不行,输出-1.ISBN号码共有10位,最后一位为校验位。An ISBN (International Standard Book Number) is a ten digit code that uniquely identifies a book. The first nine digits represent the book and the last digit is used to make sure the ISBN is correct. To verify that an ISBN number is correct, you calculate a sum that is 10 times the first digit plus 9 times the second digit plus 8 times the third digit ... all the way until you add 1 times the last digit. If the final number leaves no remainder when divided by 11, the code is a valid ISBN.
思路:比较简单,但是一些细节还是需要注意。
#include <stdio.h>
#include <string.h>
#define N 20
char s[N];
int main(){
freopen("a.txt","r",stdin);
while(scanf("%s",s)!=EOF){
int i,j,sum=0,flag = -1,res=-1;
for(i = 0;i<10;i++){
if(s[i] == '?')
flag = i;
else if(s[i] == 'X')
sum += (10-i)*10;
else
sum += (10-i)*(s[i]-'0');
}
i = (11-sum%11)%11;//一开始没有%11,导致i=11的情况
for(j = 0;11*j+i<=(10-flag)*10;j++)
if((11*j+i)%(10-flag)==0){
res = (11*j+i)/(10-flag);
break;
}
if(res==10 && flag!=9 || res==-1)
printf("-1\n");
else if(res==10 && flag==9)
printf("X\n");
else
printf("%d\n",res);
}
return 0;
}