VerifyCreditCard
SRM 396 · 2008-04-03 · by asal1
Problem Statement
You know that the Luhn formula applies for all the acceptable card numbers.
The Luhn formula works as follows.
First, separate the individual digits of the credit card number. For example:
21378 becomes
2 1 3 7 8
If there is an even number of digits, multiply each digit in an odd position by 2. Otherwise, multiply each digit in an even position by 2. Positions are 1-indexed, so the first digit is at position 1. The example number above contains an odd number of digits, so we multiply each digit in an even position by 2:
2 1 3 7 8 becomes
2 2 3 14 8
Note that the even positions refer to the original number so they don't change even when a 2-digit number appears.
Finally, take the sum of all the digits (for 2-digit numbers insert both the digits separately into the sum):
2+2+3+1+4+8 = 20
If the sum is a multiple of 10, the number is valid. Otherwise, it is invalid.
Given a
Constraints
- cardNumber will contain between 1 and 50 characters, inclusive.
- Each character in cardNumber will be a digit ('0'-'9').
"21378" Returns: "VALID"
This number has 5 digits, which is an odd number, so we multiply the digits in even positions by 2 to get: 2 2 3 14 8 The sum of the digits is 20, which is a multiple of 10, meaning it's a valid number.
"31378" Returns: "INVALID"
When we apply the Luhn formula here, the sum of the digits is 21, so the number is invalid.
"11111101" Returns: "VALID"
We multiply the digits in odd positions by 2 to get: 2 1 2 1 2 1 0 1 The sum of the digits is 10, so it's a valid card.
"50005" Returns: "VALID"
All the digits in even positions are 0 so multiplying by 2 doesn't change the number. The sum of the digits is 10, so it's a valid card.
"542987223412" Returns: "INVALID"
Submissions are judged against all 58 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class VerifyCreditCard with a public method string checkDigits(string cardNumber) · 58 test cases · 2 s / 256 MB per case