xiqe / code-train

前端算法
0 stars 0 forks source link

Validate Credit Card Number #175

Open xiqe opened 5 years ago

xiqe commented 5 years ago

Validate Credit Card Number

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:

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]

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

# reply
```js
function validate(n){
  return String(n).split('').reverse().map((x,i)=>{
    if(i%2==0) return x*1;
    return x*2>9?String(x*2)[0]*1 + String(x*2)[1]*1:x*2;
  }).reduce((s,x)=>s+=x,0)%10 == 0
}