iphone - iPhone SDK 中的信用卡验证算法

标签 iphone ios cocoa-touch ios4

谁能分享信用卡验证算法的任何示例代码。

最佳答案

卢恩算法:

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/

相关文章:

iphone - 来自自定义 .XIB 文件的 UITableViewCell 不会创建导出

objective-c - 在编写 iOS 应用程序时评论标准?

ios - 子类化 PFUser

iphone - Tab 激活时刷新 View

iOS,钥匙串(keychain) : Wrong passcode output

iphone - Objective-C/iOS : Converting an array of objects to JSON string

iphone - 如何在 UIViewController 上添加弹出 UIView(自定义类)

c++ - cpp 文件 #include 导致错误,@class 不

iphone - nsinvalidargumentexception' 原因 'an avplayeritem cannot be associated with more than one instance of avplayer'

ios - PIN 更改后连接到外围设备