题目描述
一个合法的身份证号码由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
现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。
输入格式:
输入第一行给出正整数N(≤100)是输入的身份证号码的个数。随后N行,每行给出1个18位身份证号码。
输出格式:
按照输入的顺序每行输出1个有问题的身份证号码。这里并不检验前17位是否合理,只检查前17位是否全为数字且最后1位校验码计算准确。如果所有号码都正常,则输出All passed。
输入样例1:
4
320124198808240056
12010X198901011234
110108196711301866
37070419881216001X
输出样例1:
12010X198901011234
110108196711301866
37070419881216001X
输入样例2:
2
320124198808240056
110108196711301862
输出样例2:
All passed
C++解法
- 解法1
#include<cstdio>
#include<cstring>
int w[20]={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
char change[15]={'1','0','X','9','8','7','6','5','4','3','2'};
int main(){
int n;
scanf("%d",&n);
bool flag=true;
char str[20];
for(int i=0;i<n;i++){
scanf("%s",str);
int j,last=0;
for(j=0;j<17;j++){
if(!(str[j]>='0'&&str[j]<='9')) break;
last=last+(str[j]-'0')*w[j];
}
if(j<17){
flag=false;
printf("%s\n",str);
}else{
if(change[last%11]!=str[17]){
flag=false;
printf("%s\n",str);
}
}
}
if(flag==true){
printf("All passed\n");
}
return 0;
}
思路:重点在设置flag,然后对前17位是否全为数字且最后1位校验码计算准确进行判断
- 解法2
#include <iostream>
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;
}
Java解法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] m = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
int[] w = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
int n = Integer.parseInt(br.readLine());
int i, j;
boolean pass = true;
for (i = 0; i < n; i++) {
String str = br.readLine();
char[] c = str.toCharArray();
int total = 0;
boolean isNum = true;
for (j = 0; j < 17 && isNum; j++) {
if (c[j] >= '0' && c[j] <= '9') {
total += (c[j] - '0') * w[j];
} else {
isNum = false;
}
}
total = total % 11;
if (c[17] != m[total] || !isNum) {
pass = false;
System.out.println(str);
}
}
if (pass) {
System.out.print("All passed");
}
}
}