PAT乙级1031. 查验身份证(15)

题目

链接https://www.patest.cn/contests/pat-b-practise/1031

一个合法的身份证号码由17位地区、日期编号和顺序编号加1位校验码组成。校验码的计算规则如下:
首先对前17位数字加权求和,权重分配为:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后将计算的和对11取模得到值Z;最后按照以下关系对应Z值与校验码M的值:
Z:0 1 2 3 4 5 6 7 8 9 10
M:1 0 X 9 8 7 6 5 4 3 2
现在给定一些身份证号码,请你验证校验码的有效性,并输出有问题的号码。
输入格式:
输入第一行给出正整数N(<= 100)是输入的身份证号码的个数。随后N行,每行给出1个18位身份证号码。
输出格式:
按照输入的顺序每行输出1个有问题的身份证号码。这里并不检验前17位是否合理,只检查前17位是否全为数字且最后1位校验码计算准确。如果所有号码都正常,则输出“All passed”。
输入样例1:
4
320124198808240056
12010X198901011234
110108196711301866
37070419881216001X
输出样例1:
12010X198901011234
110108196711301866
37070419881216001X
输入样例2:
2
320124198808240056
110108196711301862
输出样例2:
All passed

思路

题目说了前17位是正确输入,那么只要判断第18位即可

因为如果有一个错误需要把之前错误都输出出来,我用了结构体

其实,完全可以不用存储,只需要有错误的输出出来即可

代码

代码一 有存储+队列queue

#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <cmath>
#include<iomanip>
#include <queue> //使用队列  
using namespace std;

struct id_card
{
	char a[20];
	int flag;
};

int main()
{    
	//freopen("in.txt" , "r" , stdin);//
	int n,tmp,cnt=0;
	cin>>n;
	tmp=n;
	queue<id_card>q;  
	id_card k;
	int b[]={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
	char c[]={'1','0','X','9','8','7','6','5','4','3','2'};
	while(tmp--)
	{
		cin>>k.a;
		int i,sum=0;
		for( i=0;i<17;i++)
			sum+=(k.a[i]-'0')*b[i];
		if(k.a[i]==c[sum%11])
			{k.flag=1; cnt++;}
		else
			k.flag=0;
		q.push(k);
	};
	if(cnt==n)
		cout<<"All passed"<<endl;
	else
	{	
		id_card t;
		while(!q.empty())
		{
			t=q.front();
			if(t.flag==0)
				cout<<t.a<<endl;
			q.pop();
		}
	}
	return 0;
}

代码二 无存储

#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <cmath>
#include<iomanip>
#include <queue> //使用队列  
using namespace std;

int main()
{    
	//freopen("in.txt" , "r" , stdin);//
	char a[18];
	int n,tmp,cnt=0;
	cin>>n;
	tmp=n;
	int b[]={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
	char c[]={'1','0','X','9','8','7','6','5','4','3','2'};
	while(tmp--)
	{
		cin>>a;
		int i,sum=0;
		for(i=0;i<17;i++)
			sum+=(a[i]-'0')*b[i];
		if(a[i]==c[sum%11])
			 cnt++;
		else
			cout<<a<<endl;
	};
	if(cnt==n)
		cout<<"All passed"<<endl;
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值