Identification Number Check Digit
Problem statement
You are given an identification number as a digit string identificationNumber. Compute its check digit.
- Number positions from the left, starting at
0. - Add the digits at even positions and multiply that sum by
3. - Add the digits at odd positions to get a total.
- Return the amount needed to reach the next multiple of
10. If the total is already a multiple of10, return0.
Equivalently, return (10 - total % 10) % 10.
Practice details
For this exercise, assume positions are counted from the left and the number is supplied as a string of decimal digits. Keep any leading zeros and count positions before converting individual digits.
Function
checkDigit(identificationNumber: String) → intExamples
Example 1
identificationNumber = "39847"return = 3Even positions contain 3, 8, and 7, giving 18. Tripling gives 54. Adding 9 + 4 gives 67. The next multiple of 10 is 70, so return 3.
Example 2
identificationNumber = "12"return = 5Position 0 contains 1, so the total is 3 * 1 + 2 = 5. Adding 5 reaches 10.
Example 3
identificationNumber = "0"return = 0The total is already 0, a multiple of 10, so the check digit is 0.
Constraints
- The digit string has length from
1to12. - Every character is a decimal digit from
0through9.