[Java] Java通过Luhn算法验证信用卡卡号是否有效 →→→→→进入此内容的聊天室

来自 , 2020-10-20, 写在 Java, 查看 140 次.
URL http://www.code666.cn/view/0ab922ba
  1. public class Luhn {
  2.     public static void main(String[] args) {
  3.         System.out.println(luhnTest("49927398716"));
  4.         System.out.println(luhnTest("49927398717"));
  5.         System.out.println(luhnTest("1234567812345678"));
  6.         System.out.println(luhnTest("1234567812345670"));
  7.     }
  8.  
  9.     public static boolean luhnTest(String number){
  10.         int s1 = 0, s2 = 0;
  11.         String reverse = new StringBuffer(number).reverse().toString();
  12.         for(int i = 0 ;i < reverse.length();i++){
  13.             int digit = Character.digit(reverse.charAt(i), 10);
  14.             if(i % 2 == 0){//this is for odd digits, they are 1-indexed in the algorithm
  15.                 s1 += digit;
  16.             }else{//add 2 * digit for 0-4, add 2 * digit - 9 for 5-9
  17.                 s2 += 2 * digit;
  18.                 if(digit >= 5){
  19.                     s2 -= 9;
  20.                 }
  21.             }
  22.         }
  23.         return (s1 + s2) % 10 == 0;
  24.     }
  25. }
  26.  
  27.  
  28. //java/7117

回复 "Java通过Luhn算法验证信用卡卡号是否有效"

这儿你可以回复上面这条便签

captcha