谁能分享信用卡验证算法的任何示例代码。
最佳答案
卢恩算法:
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
关于iphone - iPhone SDK 中的信用卡验证算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7816454/