iPhone Sdk中的信用卡验证算法

VsN*_*VsN 2 iphone cocoa-touch ios4 ios

任何人都可以分享信用卡验证算法的任何示例代码.

bry*_*mac 14

Luhn算法:

http://en.wikipedia.org/wiki/Luhn_algorithm

这里有一些常用语言的示例:

http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers

从这个链接,大多数CC使用Luhn(见表):

http://en.wikipedia.org/wiki/Credit_card_number

从上面的链接(rosettacode):

 - (NSMutableArray *) toCharArray {

     NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self length]];
     for (int i=0; i < [self length]; i++) {
         NSString *ichar  = [NSString stringWithFormat:@"%c", [self characterAtIndex:i]];
         [characters addObject:ichar];
     }

     return [characters autorelease];
 }

 + (BOOL) luhnCheck:(NSString *)stringToTest {

     NSMutableArray *stringAsChars = [stringToTest toCharArray];

     BOOL isOdd = YES;
     int oddSum = 0;
     int evenSum = 0;

     for (int i = [stringToTest length] - 1; i >= 0; i--) {

         int digit = [(NSString *)[stringAsChars objectAtIndex:i] intValue];

         if (isOdd) 
             oddSum += digit;
         else 
             evenSum += digit/5 + (2*digit) % 10;

         isOdd = !isOdd;                 
     }

     return ((oddSum + evenSum) % 10 == 0);
 }
 // results
 BOOL test0 = [self luhnCheck:@"49927398716"]; //Result = YES
 BOOL test1 = [self luhnCheck:@"49927398717"]; //Result = NO
 BOOL test2 = [self luhnCheck:@"1234567812345678"]; //Result = NO                  
 BOOL test3 = [self luhnCheck:@"1234567812345670"]; //Result = YES  
Run Code Online (Sandbox Code Playgroud)