PTA 1031 查验身份证(详解加代码)

终于!让我缓和了下,前阵子做题有点小崩溃,思路跟不上。今天这个就让我舒服一点。
解析:7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2}存入数组 遍历字符串相乘=sum sum+=sum z=sum%11
m存入数组 索引z取值 比较字符串最后一位

public class Pta_1031 {
    static int[] qz = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};//权重
    static char[] m_index = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};//校验码


    public static void main(String[] args) throws IOException {
        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
        int time = Integer.parseInt(buf.readLine());
        int num = 0;
        for (int i = 0; i < time; i++) {
            String str = buf.readLine();
            if (test2(str)) {
                num++;
                System.out.println(str);
            }
        }
        if (num == 0) {
            System.out.println("All passed");
        }
    }

    public static boolean test2(String str) {
        int sum = 0;
        int z = 0;
        for (int i = 0; i < str.length() - 1; i++) {
            //判断前17位是否包含非法字符,如果有,直接返回真,后面不执行,因为有非法字符无法计算。
            if ('0' > str.charAt(i) || str.charAt(i) > '9') {
                return true;
            }
            //得到数字,进行权重相乘,存到sum
            int res = str.charAt(i) - 48;
            sum += res * qz[i];
        }
        //取模得到z,根据z作为索引得到校验码
        z = sum % 11;
        if (m_index[z] != str.charAt(str.length() - 1)) {
            return true;
        }
        return false;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值