PAT-乙-1031 1031 查验身份证 (15 分)
代码
#include <iostream>
using namespace std;
int main() {
int weight[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
char check[] = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2', '1'};
int n;
cin>>n;
int count = 0;
for(int i=0; i<n; i++) {
bool flag = true;
int sum = 0;
string s;
cin>>s;
if(s.length()!=18) {
flag = false;
} else {
for(int j=0; j<s.length()-1; j++) {
if(s.at(j)<'0' || s.at(j)>'9') {
flag = false;
break;
} else {
sum += (s.at(j)-'0') * weight[j];
}
}
if(flag) {
char last = check[sum%11];
if(last!=s.at(17)) {
flag = false;
}
}
}
if(flag){
count++;
}
else{
cout<<s<<endl;
}
}
if(count==n){
cout<<"All passed"<<endl;
}
return 0;
}
注解
把权重写在数组中,数组与位置对应,是种好的做法。