在JavaScript中实现Luhn算法

时间:2013-02-16 00:59:30

标签: javascript luhn

我正在尝试将Luhm算法实现移植到C#中。我把它移植了,我认为它正在工作,但我无法获得合法的卡片验证。我的AMEX验证很好,但我的两个VISA拒绝这样做。这是代码:

luhn = function (number) {
    var _deltas = [0, 1, 2, 3, 4, -4, -3, -2, -1, 0],
        _checksum = 0,
        _digits = [],
        i,
        j;

    while (number != 0) {
        _digits.push(parseInt((number % 10), 10));

        number = parseInt((number / 10), 10);
    }

    for (i = (_digits.length - 1), j = _digits.length; i > -1; i--) {
        _digit = _digits[i];
        _checksum += _digit;
        _checksum += ((((i - j) % 2) === 0) ? _deltas[_digit] : 0);
    }

    return ((_checksum % 10) === 0);
};

有人能指出我正确的方向吗?我认为这在C#版本中运行良好,但现在我有疑问......提前谢谢!

3 个答案:

答案 0 :(得分:0)

{
    "diffs": [{
        "before": null,
        "after": {
            "org.bitbucket.codezarvis.api.dto.DistrictDocument": {
                "districtId": {
                    "mostSigBits": -917,
                    "leastSigBits": -562
                },
                "state": null,
                "subDistricts": {
                    "array": [{
                        "subDistrictId":111,
                        "longitudeOfPoi": {
                            "string": "1.52256"
                        },                      
                        "latitudeOfPoi": {
                            "string": "42.543528"
                        }
                    }
                }
            }]
        }

此处最佳解决方案

根据

传递所有测试用例

,功劳归于

答案 1 :(得分:0)

对于其他人,下面是我提交的测试解决方案:)

function validateCard(num){
    var oddSum = 0;
    var evenSum = 0;
    var numToString = num.toString().split("");
    for(var i = 0; i < numToString.length; i++){
      if(i % 2 === 0){
        if(numToString[i] * 2 >= 10){
          evenSum += ((numToString[i] * 2) - 9 );
        } else {
          evenSum += numToString[i] * 2;
        }
      } else {
        oddSum += parseInt(numToString[i]);
      }
    }
    return (oddSum + evenSum) % 10 === 0;
  }
console.log(validateCard(41111111111111111));

希望这会有所帮助。米奇-来自https://spangle.com.au

答案 2 :(得分:0)

此解决方案接受数组作为参数。如果有效返回true,无效返回false。

function validateCred(arr) {
    let sumArray = [];
    let numHolder = null;
    let everySecondNumber = 1;
    for (let i = arr.length - 1; i >= 0; i--) {
        if (everySecondNumber % 2 === 0) {
                numHolder = arr[i] * 2;
            if (numHolder > 9) {
                numHolder -= 9;
            }
        } else {
            numHolder = arr[i];
        }
        sumArray.push(numHolder);
        everySecondNumber++;
    }
    totalSum = sumArray.reduce((acc,val) => acc + val, 0);
    if (totalSum % 10 == 0) {
        return true;
    } else {
        return false;
    }
}