Zerojudge a020. 身分證檢驗


評分:1 分,滿分為 5。

題目連結

題意

給一個字串,判斷是不是一個合法的身分證字號,判斷是否為身分證字號的規則在題目有詳細說明。

解題方法

我們跟著題目給的步驟一一進行解題

  1. 將第一個英文字母轉成對應的數字

乍看,我們可以直接用 A = 10, B = 11, C = 12… 直接把字母 – A + 10 轉換,但是,後面其實有一些不符合這個規則的字母。但是,我們還是可以發現,有一段一段的字母是連續的,其他不是。我們可以針對每個連續的區間做處理,剩下就特別判斷。

2. 把英文轉成的數字個位數 * 9 + 十位數

這部分可以直接用 % 10 和 / 10 拿到個位數和十位數

3. 各數字從右到左依次乘1、2、3、4....8

這部分可以直接用迴圈從左跑到右,並開變數紀錄總和

剩下就把算好的東西加起來再加上最後一個數字,判斷是否整除 10 即可

#include <bits/stdc++.h>
using namespace std;
int eng_to_num(char c) {
	int res = 0;
	if('A' <= c && c <= 'H') res = c-'A'+10;
	else if(c == 'I') res = 34;
	else if('J' <= c && c <= 'N') res = c-'J'+18;
	else if(c == 'O') res = 35;
	else if('P' <= c && c <= 'V') res = c-'P'+23;
	else if(c == 'W') res = 32;
	else if(c == 'X') res = 30;
	else if(c == 'Y') res = 31;
	else if(c == 'Z') res = 33;
	return res;
}
int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	string s;
	cin >> s;
	int step1 = eng_to_num(s[0]);
	int step2 = step1 % 10 * 9 + step1 / 10;
	int step3 = 0;
	int now = 8;
	for(int i = 1;i < s.size() - 1;i++) {
		step3 += (int)(s[i] - '0') * now;
		now --;
	}
	int step4 = step2 + step3 + (s.back() - '0');
	if(step4 % 10 == 0) cout << "real\n";
	else cout << "fake\n";
}

圖片來源: https://swf.com.tw/?p=94


發表迴響

Blog at WordPress.com.

探索更多來自 Coding Prep 演算法資料結構教學 的內容

立即訂閱即可持續閱讀,還能取得所有封存文章。

Continue reading