题目:现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。
我的代码:
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int find(int n,int a[]){
for(int i = 0;i <10;i++){
if(a[i] == n) return n;
}
}
int main(){
char a[100][18];
int w[17] = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
int z[11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
char m[11] = {'1', '0', 'X' ,'9', '8', '7' ,'6' ,'5', '4', '3', '2'};
int flag = 0;
int n,num = 0,sum = 0;
char s17;
cin>>n;
for(int i = 0;i < n;i++)
for(int j = 0;j < 18;j++)
cin>>a[i][j];
for(int i = 0;i < n;i++){
flag = 0,sum = 0;
for(int j = 0;j < 17;j++){
if(a[i][j] == 'X') {
flag = 1;
}
else sum += (a[i][j] - '0') * w[j];
}
sum %= 11;
s17 = find(sum,z);
if(m[s17] != a[i][17] ) flag = 1;
if(flag == 1){
for(int k = 0;k < 18;k++){
cout<<a[i][k];
}
cout<<endl;
num++;
}
}
if(num == 0) cout<<"All passed";
return 0;
}
评注:(1)Z[]数组没有必要列出来再求索引,因为里面的元素跟i是一致的。(2)自己的代码用了两个标志位num和flag,参考代码里面只用了一个,而且参考代码中更加直接直观。
参考代码:
链接:https://www.nowcoder.com/questionTerminal/779a72a420744b1d9c0ec7b7a8dd8f39
来源:牛客网
#include<iostream>
#include<string>
using namespace std;
int main()
{
int weight[17]={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
char M[11]={'1','0','x','9','8','7','6','5','4','3','2'};
int N;
cin>>N;
string A;
int flag=1;//whether the data is all passed
for(int i=0;i<N;++i)
{
int sum=0;
int is_wrong=0;
cin>>A;
for(int j=0;j<17;++j)
{
if(A[j]<'0'||A[j]>'9')
{
cout<<A<<endl;
flag=0;
is_wrong=1;
break;
}
sum+=(A[j]-'0')*weight[j];
}
//judge the last char
int z=sum%11;
char right=M[z];
if(A[17]!=right&&is_wrong==0)
{
flag=0;
cout<<A<<endl;
}
}
if(flag)
{
cout<<"All passed"<<endl;
}
return 0;
}