Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - 难以构建Luhn算法(Difficulty in constructing Luhn's algorithm)

I want to construct Luhn's algorithm which is usually used to validate credit card numbers.

(我想构建通常用于验证信用卡号的Luhn算法。)

Luhn's algorithm works like this:

(Luhn的算法如下所示:)

  • Isolate every digit, starting from the right moving left, doubling every second one.

    (隔离每个数字,从右移左开始,每秒增加一倍。)

    If the doubled value is greater than 9, subtract 9 from it.

    (如果加倍的值大于9,则减去9。)

  • Sum all the transformed digits.

    (对所有转换后的数字求和。)

  • The original number valid according to Luhn's algorithm if and only if the sum ends in a 0.

    (当且仅当总和以0结尾时,原始数字才根据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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...