-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidate_credit_num.cpp
51 lines (34 loc) · 1.68 KB
/
Validate_credit_num.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
In this Kata, you will implement the Luhn Algorithm, which is used to help validate credit card numbers.
Given a positive integer of up to 16 digits, return true if it is a valid credit card number, and false if it is not.
Here is the algorithm:
Double every other digit, scanning from right to left, starting from the second digit (from the right).
Another way to think about it is: if there are an even number of digits, double every other digit starting with the first; if there are an odd number of digits, double every other digit starting with the second:
1714 ==> [1*, 7, 1*, 4] ==> [2, 7, 2, 4]
12345 ==> [1, 2*, 3, 4*, 5] ==> [1, 4, 3, 8, 5]
891 ==> [8, 9*, 1] ==> [8, 18, 1]
If a resulting number is greater than 9, replace it with the sum of its own digits (which is the same as subtracting 9 from it):
[8, 18*, 1] ==> [8, (1+8), 1] ==> [8, 9, 1]
or:
[8, 18*, 1] ==> [8, (18-9), 1] ==> [8, 9, 1]
Sum all of the final digits:
[8, 9, 1] ==> 8 + 9 + 1 = 18
Finally, take that sum and divide it by 10. If the remainder equals zero, the original credit card number is valid.
18 (modulus) 10 ==> 8 , which is not equal to 0, so this is not a valid credit card number
*/
class Kata {
public:
static int validate(long long int n) {
std::string num (std::to_string(n));
bool ne = num.size() & 1;
int sum = 0;
for (int i = 0; i < num.size(); ++i)
if (ne) {
sum += (i + 1) & 1 ? num[i] - '0' : ( (num[i] - '0') * 2 > 9 ? (num[i] - '0') * 2 - 9 : (num[i] - '0') * 2);
}
else {
sum += !((i + 1) & 1) ? num[i] - '0' : ( (num[i] - '0') * 2 > 9 ? (num[i] - '0') * 2 - 9 : (num[i] - '0') * 2);
}
return !(sum % 10);
}
};