信用卡验证算法在iPhone Sdk [英] Credit Card Validation Algorithm in iPhone Sdk

查看:120
本文介绍了信用卡验证算法在iPhone Sdk的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can anyone please share any sample code for Credit Card Validation Algorithm.

推荐答案

Luhn算法:

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

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

Here some samples for common languages:

http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers

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

From this link, most CCs use Luhn (see the table):

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

从上面的链接(rosettacode):

From the link above (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 Sdk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆