一个合法的身份证号码由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 10M:1 0 X 9 8 7 6 5 4 3 2
现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。
输入格式:
输入第一行给出正整数N(≤100)是输入的身份证号码的个数。随后N行,每行给出1个18位身份证号码。
输出格式:
按照输入的顺序每行输出1个有问题的身份证号码。这里并不检验前17位是否合理,只检查前17位是否全为数字且最后1位校验码计算准确。如果所有号码都正常,则输出All passed。
输入样例1:
432012419880824005612010X19890101123411010819671130186637070419881216001X
输出样例1:
12010X19890101123411010819671130186637070419881216001X
输入样例2:
2320124198808240056110108196711301862
输出样例2:
All passed
代码
import java.util.Scanner;class Person{String ID;int sumWeight = 0;char check;boolean vaild = true;}public class Main {static int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};static char[] check = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};public static void main(String[] args) {int number;Scanner input = new Scanner(System.in);number = input.nextInt();/** Create some objects */Person[] person = new Person[number];for(int i = 0; i < number; i++) {person[i] = new Person();}/** Input the data */for(int i = 0; i < number; i++) {person[i].ID = input.next();}/** Is someone invaild before 18 bits? */for(int i = 0; i < number; i++) {for(int j = 0; j < 17; j++) {if(person[i].ID.charAt(j) >= '0' && person[i].ID.charAt(j) <= '9') {continue;}else {person[i].vaild = false;}}}/** Compte the weightID of vaild person */for(int i = 0; i < number; i++) {if(!person[i].vaild) {continue;}else {for(int j = 0; j < 17; j++) {person[i].sumWeight += (person[i].ID.charAt(j) - '0') * weight[j];}/* Find the check */person[i].check = check[person[i].sumWeight % 11];if(person[i].check == person[i].ID.charAt(17)) {person[i].vaild = true;}else {person[i].vaild = false;}}}/** Display the result */int counter = 0;for(int i = 0; i < number; i++) {if(person[i].vaild) {counter++;}}if(counter == number) {System.out.println("All passed");}for(int i = 0; i < number; i++) {if(!person[i].vaild) {System.out.println(person[i].ID);}}}}
