PAT Basic Level 1031 查验身份证 (15 分)

题目链接:

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

我的未AC代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
using namespace std;


int main() {
	int n;
	vector<string> str(100);
	vector<bool> str_(100, false);
	char M[] = { '1','0','X','9','8','7','6','5','4','3','2' };
	int quan[] = { 7,9,0,5,8,4,2,1,6,3,7,9,10,5,8,4,2 };
	while (cin >> n) {
		for (int i = 0; i < n; i++)
		{
			cin >> str[i];
			int sum = 0;
			for (int j = 0; j < 16; j++)
				sum += quan[j] * str[i][j];
			sum %= 11;
			if (M[sum] == str[i][16])
				str_[i] = true;
		}
		//检验前17位是否都是数字
		for (int i = 0; i < n; i++) {
			for (int j = 0; j <= 16; j++) {
				if (str[i][j] > '9' || str[i][j] < '0') {
					str_[i] = false;
					break;
				}
			}
		}
		int cnt = 0;
		for (int i = 0; i < n; i++) {
			if (!str_[i])
			{
				cout << str[i] << endl;
				cnt++;
			}
		}
		if (cnt == 0)
			cout << "All passed"<<endl;
	}
}

未AC代码(这题有问题):

#include <iostream>
#include <cstdio>

using namespace std;

int w[20]={ 7,9,0,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;
    bool flag=true;//记录所有的身份证是否合法
    scanf("%d",&N);
    char str[20];
    for(int i=0;i<N;i++){
        int j,last=0;//记录校验码
        scanf("%s",str);
        for(j=0;j<17;j++){
            if(str[j]>'9'||str[j]<'0')
                break;
            last=(str[j]-'0')*w[j]+last;
        }
        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;
}

猜你喜欢

转载自blog.csdn.net/qq_41755143/article/details/86565902