PAT乙级1031

题目链接

https://pintia.cn/problem-sets/994805260223102976/problems/994805290334011392

题解

emmm。对于每个身份证号,判断前17位是否合法,并计算其与对应权重积之和,最后判断校验位是否合法。

// PAT BasicLevel 1031
// https://pintia.cn/problem-sets/994805260223102976/problems/994805290334011392

#include <iostream>
#include <string>
using namespace std;

int main()
{
    // 正确校验码
    char M[] = { '1','0','X','9','8','7','6','5','4','3','2'};
    // 前17位的比重
    int weight[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    // 身份证号个数
    int n;
    cin >> n;

    // 前17位乘以权重之和
    int sum;
    // 合法身份证号的个数
    int legalCount=0;
    // 当前身份证号是否合法
    bool isLegal;
    // 当前身份证号
    string str;

    // 获取每个身份证号并判断
    for(int i=0;i<n;++i){
        cin >> str;
        // 初始化
        sum=0;
        isLegal=true;

        // 计算前17位乘以权重之和并判断前17位合法性
        for(int i=0;i<17;++i){
            if (isdigit(str[i])){
                sum += (str[i] - '0')*weight[i];
            }
            // 出现非数字,非法,结束sum的计算
            else{
                isLegal=false;
                break;
            }
        }

        // 如果前17位合法,判断校验码是否合法
        if(isLegal){
            isLegal = (M[sum % 11]==str[17]);
        }

        // 身份证号非法则输出
        if(!isLegal){
            cout << str << endl;
        }
        // 合法则计数
        else{
            legalCount++;
        }
    }

    // 全部身份证号合法
    if(legalCount==n){
        cout << "All passed";
    }

    //system("pause");
    return 0;
}

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


posted @ 2019-08-07 23:48  臭咸鱼  阅读(193)  评论(0编辑  收藏  举报