Sha256: 0370fa0f9268ffadceae6a8f600ce3165d3448d195b63a8b5989d0e028ba6cb5

Contents?: true

Size: 1.09 KB

Versions: 226

Compression:

Stored size: 1.09 KB

Contents

#import "LuhnExample.h"

@implementation Luhn

- (instancetype)initWithString:(NSString *)string {
    self = [super init];
    
    if (self) {
        _isValid = [Luhn validateString:string];
    }
    
    return self;
}

+ (BOOL)validateString:(NSString *)string {
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""]; //!OCLint
    
    if (string.length < 2) {
        return NO;
    }
    
    NSCharacterSet *digitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([string rangeOfCharacterFromSet:digitCharacterSet].location != NSNotFound) {
        return NO;
    }
    
    int total = 0;
    
    for (int i = 1; i <= string.length; i++) {
        NSString *character = [NSString stringWithFormat:@"%c", [string characterAtIndex:string.length - i]];
        int digit = character.intValue;
        
        if (i % 2 == 0) {
            digit *= 2;
            if (digit > 9) {
                digit -= 9;
            }
        }
        
        total += digit;
    }
    
    if (total % 10 == 0) {
        return YES;
    }
    
    return NO;
}

@end

Version data entries

226 entries across 226 versions & 1 rubygems

Version Path
trackler-2.2.1.139 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.138 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.137 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.136 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.135 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.134 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.133 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.132 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.131 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.130 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.129 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.128 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.127 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.126 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.125 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.124 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.123 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.122 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.121 tracks/objective-c/exercises/luhn/LuhnExample.m
trackler-2.2.1.120 tracks/objective-c/exercises/luhn/LuhnExample.m