Simple java ID card 18th-digit algorithm

Source: Internet
Author: User
Public class identitynum {

Public static void main (string [] args ){
System. out. println (getlastidnum ("37018319880321312 "));
    }

/**
* Name: calculate the last digit of the 18-digit ID card.
* Function: calculate the last digit based on the ID number of the first 17 digits.
* Algorithm of the last digit of the ID card:
* 1. Multiply the first 17 digits of the ID card number by the weights: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 2
* (For example, multiply the first digit by 7, the second digit by 9, and so on)
* 2. Then sum all the products above
* 3. Take the obtained mod and mod as 11 (% 11) and obtain a number smaller than 11 (0 to 11)
* 4. Then find the last digit from the first digit of the verification code: 1 0x9 8 7 6 5 4 3 2
* If 0 is obtained, the first digit is 1. If 1 is obtained, the second digit is 0.
* If the result is 2, it corresponds to the third digit: x. If the result is 3, it corresponds to the fourth digit: 9, and so on.
* 5. The last digit of the ID card is obtained.
*/
Public static character getlastidnum (string preids ){
Character lastid = null;
// When the input string does not contain 17 digits, it cannot be calculated and is directly returned.
If (preids = null & preids. length () <17 ){
Return null;
        }
Int [] weightarray = {,}; // Weight array
String vcode = "10x98765432"; // verification code string
Int sumnum = 0; // The first 17 is the number multiplied by the right and then the sum is obtained.
       
// Multiply the weights cyclically and then sum them.
For (int I = 0; I <17; I ++ ){
Int index = integer. parseint (preids. charat (I) + "");
Sumnum = sumnum + index * weightarray [I]; // multiply by the weight and then sum
        }
       
Int modnum = sumnum % 11; // modulo
Lastid = vcode. charat (modnum); // find the corresponding number from the verification code
       
Return lastid;
    }
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.