一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下:
首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后将计算的和对11取模得到值Z;最后按照以下关系对应Z值与校验码M的值:
Z:0 1 2 3 4 5 6 7 8 9 10
M:1 0 X 9 8 7 6 5 4 3 2
现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。
原题链接
#include
#include
using namespace std;
int main() {
int n;
cin >> n;
int zm[11] = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
int weight[17] = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
string str;
int sum; // calculate sum
int flag = 0; // if there is no wrong id
for (int i = 0; i < n; i++) { // cin and then cout
sum = 0;
cin >> str;
int flag2 = 0;
for (int j = 0; j < 17; j++) {
if (str[j] <'0' || str[j] > '9') {// 如果有不是字符的,就报错然后输出
cout << str << endl;
flag = 1;
flag2 = 1;// 跳过下面的步骤,直接检测下一个代码
break;
}
}
for (int j = 0; j < 17 && flag2== 0; j++) {// 全是数字
sum += (str[j] - '0') * weight[j];
}
if (zm[sum%11] != str[17] && flag2== 0) {
cout << str << endl;
flag = 1;
}
}
if (flag==0) cout <<"All passed";// no wrong id
return 0;
}
char - '0'
,不要用stoi()
,因为这个函数要求输入参数是字符串。参考:https://www.cplusplus.com/reference/string/stoi/#include
using namespace std;
int a[17] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
int b[11] = {1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2};
string s;
bool isTrue() {
int sum = 0;
for (int i = 0; i < 17; i++) {
if (s[i] < '0' || s[i] > '9') return false;
sum += (s[i] - '0') * a[i];
}
int temp = (s[17] == 'X') ? 10 : (s[17] - '0');
return b[sum%11] == temp;
}
int main() {
int n, flag = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> s;
if (!isTrue()) {
cout << s << endl;
flag = 1;
}
}
if (flag == 0) cout << "All passed";
return 0;
}