PAT-BASIC1031——查验身份证

我的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++解题报告:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值