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

来自 , 2019-03-28, 写在 Objective-C, 查看 142 次.
URL http://www.code666.cn/view/2377f9eb
  1. - (NSMutableArray *) toCharArray {
  2.  
  3.         NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self length]];
  4.         for (int i=0; i < [self length]; i++) {
  5.                 NSString *ichar  = [NSString stringWithFormat:@"%c", [self characterAtIndex:i]];
  6.                 [characters addObject:ichar];
  7.         }
  8.  
  9.         return [characters autorelease];
  10. }
  11.  
  12. + (BOOL) luhnCheck:(NSString *)stringToTest {
  13.  
  14.         NSMutableArray *stringAsChars = [stringToTest toCharArray];
  15.  
  16.         BOOL isOdd = YES;
  17.         int oddSum = 0;
  18.         int evenSum = 0;
  19.  
  20.         for (int i = [stringToTest length] - 1; i >= 0; i--) {
  21.  
  22.                 int digit = [(NSString *)[stringAsChars objectAtIndex:i] intValue];
  23.  
  24.                 if (isOdd)
  25.                         oddSum += digit;
  26.                 else
  27.                         evenSum += digit/5 + (2*digit) % 10;
  28.  
  29.                 isOdd = !isOdd;                          
  30.         }
  31.  
  32.         return ((oddSum + evenSum) % 10 == 0);
  33. }
  34.  
  35. BOOL test0 = [self luhnCheck:@"49927398716"]; //Result = YES
  36. BOOL test1 = [self luhnCheck:@"49927398717"]; //Result = NO
  37. BOOL test2 = [self luhnCheck:@"1234567812345678"]; //Result = NO                                   
  38. BOOL test3 = [self luhnCheck:@"1234567812345670"]; //Result = YES
  39. //objectc/7114

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

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

captcha