信用卡校正位演算法THE LUHN MOD-10

來源:互聯網
上載者:User

沒什麼要說的,只是做個備份~

---------------------------------------- 我是分割線 ---------------------------------------------

按照ISO 2894 中支付卡校正位的演算法 The Luhn Mod-10 Method 規定:

1、對卡號上的每位元字乘以權重。其規則是,如果卡號數字個數是偶數,則第一位乘以2,否則就乘以1,然後以後分別是,1,2,1,2,1,2;
2、如果每位元字乘以權重後超過9 ,則需要減去 9;
3、將所有的處理過的加權數字求和,用 數字 10 求模運算;
4、餘數應該是0,否則可能是輸入錯誤。也可能是一個假號。

 順手PHP簡單實現下,實際情境前端驗證好一些,例如JS。

function check_card($card){    if (!is_numeric($card)) return False;    $card_len = strlen($card);    $i = 0;    $num_i = array();    do{        if (!$i){            $num_x = $card_len % 2 ? 1 : 2;        } else {            $num_x = $num_x == 1 ? 2 : 1;            }        $num_i[$i] = (int)$card[$i] * $num_x;        $num_i[$i] = $num_i[$i] > 9 ? $num_i[$i] - 9 : $num_i[$i];    }while(isset($card[++$i]));    $num_sum = array_sum($num_i);    return $num_sum % 10 ? False : True;}

PS:當個初級面試題啥的應該不錯~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.