PAT 1031 查驗身份證(15)(C++&Python)

1031 查驗身份證(15)(15 分)python

一個合法的身份證號碼由17位地區、日期編號和順序編號加1位校驗碼組成。校驗碼的計算規則以下:ios

首先對前17位數字加權求和,權重分配爲:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};而後將計算的和對11取模獲得值Z;最後按照如下關係對應Z值與校驗碼M的值:git

Z:0 1 2 3 4 5 6 7 8 9 10\ M:1 0 X 9 8 7 6 5 4 3 2spa

如今給定一些身份證號碼,請你驗證校驗碼的有效性,並輸出有問題的號碼。code

輸入格式:ci

輸入第一行給出正整數N(<= 100)是輸入的身份證號碼的個數。隨後N行,每行給出1個18位身份證號碼。input

輸出格式:string

按照輸入的順序每行輸出1個有問題的身份證號碼。這裏並不檢驗前17位是否合理,只檢查前17位是否全爲數字且最後1位校驗碼計算準確。若是全部號碼都正常,則輸出「All passed」。it

輸入樣例1:io

4
320124198808240056
12010X198901011234
110108196711301866
37070419881216001X

輸出樣例1:

12010X198901011234
110108196711301866
37070419881216001X

輸入樣例2:

2
320124198808240056
110108196711301862

輸出樣例2:

All passed

C++: 

#include<iostream>
#include<string>
using namespace std;
int main(){
	int n, sum, flag ;
	cin >> n;
	string s;
	int a[17] = { 7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2 };
	int num = 0;
	char c[11] = { '1','0','X','9','8','7','6','5','4','3','2' };
	for (int i = 0; i<n; i++){
		sum = flag = 0;
		cin >> s;
		for (int j = 0; j<17; j++){           //需保證前17位全爲數字
			if (isdigit(s[j]))
				sum = sum + ((int)s[j] - '0')*a[j];
			else {
				cout << s << endl;
				flag = 1;
				break;
			}
		}
		if (!flag) {
			sum %= 11;
			if (s[17] != c[sum]) {
				cout << s << endl;
				continue;
			}
		}
		num++;
	}
	if (num == n)
		cout << "All passed";
	return 0;
}

Python: 

 

import math
import numpy as np
if __name__=='__main__':
    weight=np.array([7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2])
    judge=['1','0','X','9','8','7','6','5','4','3','2']
    n=int(input())
    count=0
    for i in range(n):
        tmp=input()
        key=0
        if tmp[0:len(tmp)-1].isdigit():
            id=np.array([int(tmp[i]) for i in range(len(tmp)-1)])
            key=np.sum(id*weight)%11
        if (not tmp[0:len(tmp)-1].isdigit()) or judge[key]!=tmp[len(tmp)-1] :
            print(tmp)
            count+=1
    if count==0:
        print("All passed")
相關文章
相關標籤/搜索