I want to construct Luhn's algorithm which is usually used to validate credit card numbers.
(我想构建通常用于验证信用卡号的Luhn算法。)
Luhn's algorithm works like this:(Luhn的算法如下所示:)
function isValid(number) {
return LuhnDigitSum(number) % 10 === 0;
}
function LuhnDigitSum(number) {
let sum = 0;
let num_str = number.toString();
let reversed_num = num_str.split("").reverse().join("");
for (let i = 0; i < reversed_num.length; i++) {
let digit = parseInt(reversed_num[i]);
if (i % 2 !== 0 && (digit * 2) <= 9) {
digit = digit * 2;
sum += digit;
}
if (i % 2 !== 0 && (digit * 2) > 9) {
digit = (digit * 2) - 9;
sum += digit;
}
if (i % 2 === 0) {
sum += digit;
}
}
return sum;
}
When i run the code, the card numbers appeared to be invalid when they are supposed to be valid, and adding to that, the sum value were incorrect.
(当我运行代码时,卡号应该是有效的时似乎无效,此外,总和值不正确。)
Your help is much appreciated.
(非常感谢您的帮助。)
Thanks!!(谢谢!!)
ask by Hui San Chiam translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…