我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805290334011392
题目描述:
知识点:字符串
思路:用一个vector保存错误的身份证号码
如果题目没有要求在所有号码都正常的情况下输出"All passed",我们完全可以边读取数据边处理。不过既然题目有了这个要求,我们就得先把错误的身份证号码都保存进一个vector中,根据该vector是否为空来判断是输出"All passed"还是输出错误的身份证号码。
时间复杂度是O(n),其中n为输入的身份证号码数。空间复杂度是O(m),其中m为不正常的身份证号码数。
C++代码:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
bool isValidString(string s, int weights[], char checkCodes[]);
int main(){
int weights[18] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
char checkCodes[11] = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
int n;
cin >> n;
vector<string> wrongStrings;
string tempString;
for(int i = 0; i < n; i++){
cin >> tempString;
if(!isValidString(tempString, weights, checkCodes)){
wrongStrings.push_back(tempString);
}
}
if(wrongStrings.size() == 0){
cout << "All passed" << endl;
}else{
for(int i = 0; i < wrongStrings.size(); i++){
cout << wrongStrings[i] << endl;
}
}
return 0;
}
bool isValidString(string s, int weights[], char checkCodes[]){
int result = 0;
for(int i = 0; i < 17; i++){
result += (s[i] - '0') * weights[i];
}
if(s[17] == checkCodes[result % 11]){
return true;
}else{
return false;
}
}
C++解题报告: