生活随笔
收集整理的這篇文章主要介紹了
牛客网_PAT乙级_1031. 查验身份证(15)【class new一个数组】
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
心得(new,if短路原理)
new[](new的數(shù)組版)要求元素對(duì)象的類型必須具有默認(rèn)構(gòu)造函數(shù)(內(nèi)建類型的“默認(rèn)構(gòu)造函數(shù)”是什么也不做),否則將不能使用new[]。
???突然發(fā)現(xiàn),這道題何必用new?用vector<ID> id不是很好嗎?
題目描述
一個(gè)合法的身份證號(hào)碼由17位地區(qū)、日期編號(hào)和順序編號(hào)加1位校驗(yàn)碼組成。校驗(yàn)碼的計(jì)算規(guī)則如下:
首先對(duì)前17位數(shù)字加權(quán)求和,權(quán)重分配為:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后將計(jì)算的和對(duì)11取模得到值Z;最后按照以下關(guān)系對(duì)應(yīng)Z值與校驗(yàn)碼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
現(xiàn)在給定一些身份證號(hào)碼,請(qǐng)你驗(yàn)證校驗(yàn)碼的有效性,并輸出有問(wèn)題的號(hào)碼。
輸入描述:
輸入第一行給出正整數(shù)N(<= 100)是輸入的身份證號(hào)碼的個(gè)數(shù)。隨后N行,每行給出1個(gè)18位身份證號(hào)碼。
輸出描述:
按照輸入的順序每行輸出1個(gè)有問(wèn)題的身份證號(hào)碼。這里并不檢驗(yàn)前17位是否合理,只檢查前17位是否全為數(shù)字且最后1位校驗(yàn)碼計(jì)算準(zhǔn)確。如果所有號(hào)碼都正常,則輸出“All passed”。
輸入例子:
4
320124198808240056
12010X198901011234
110108196711301866
37070419881216001X
輸出例子:
12010X198901011234
110108196711301866
37070419881216001X
代碼
使用了短路原理:
92行:printCount == 0 && cout << "All passed";
相當(dāng)于: if (printCount == 0)cout << "All passed";
#include<iostream>
#include<string>
using namespace std
;int WEIGHT
[] = { 7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2 };class ID
{
public
:string num
;int intNum
[18] = { -1 };bool valid
= true
;void input(string
);void checkChar();void checkNum();
};
void ID
::input(string str
)
{this
->num
= str
;
}
void ID
::checkChar()
{int i
;for (i
= 0; i
< 17; i
++){if (this
->num
[i
] < '0' || this
->num
[i
] >'9'){this
->valid
= false
;return;}this
->intNum
[i
] = this
->num
[i
] - 48;}
}
void ID
::checkNum()
{int i
;int sum
= 0;for (i
= 0; i
< 17; i
++){sum
+= this
->intNum
[i
] * WEIGHT
[i
];}sum
%= 11;switch (sum
){case 0:if (this
->num
[17] == '1')break;case 1:if (this
->num
[17] == '0')break;case 2:if (this
->num
[17] == 'X')break;case 3:if (this
->num
[17] == '9')break;case 4:if (this
->num
[17] == '8')break;case 5:if (this
->num
[17] == '7')break;case 6:if (this
->num
[17] == '6')break;case 7:if (this
->num
[17] == '5')break;case 8:if (this
->num
[17] == '4')break;case 9:if (this
->num
[17] == '3')break;case 10:if (this
->num
[17] == '2')break;default:this
->valid
= false
;}
}int main()
{int total
;cin
>> total
;ID
*pID
= new ID
[total
];int i
;string str
;for (i
= 0; i
< total
; i
++){cin
>> str
;(pID
+ i
)->input(str
);(pID
+ i
)->checkChar();if ((pID
+ i
)->valid
== false
)continue;(pID
+ i
)->checkNum();}int printCount
= 0;for (i
= 0; i
< total
; i
++){if ((pID
+ i
)->valid
== false
){cout
<< (pID
+ i
)->num
<< endl
;printCount
++;}}printCount
== 0 && cout
<< "All passed";system("pause");
}
總結(jié)
以上是生活随笔為你收集整理的牛客网_PAT乙级_1031. 查验身份证(15)【class new一个数组】的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。