-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathLargestSeriesProductExample.m
63 lines (45 loc) · 1.89 KB
/
LargestSeriesProductExample.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#import "LargestSeriesProductExample.h"
@implementation LargestSeriesProduct {
NSArray<NSNumber *> *_numbers;
}
- (instancetype)initWithNumberString:(NSString *)numberString {
if (self = [super init]) {
NSMutableArray<NSNumber *> *numbers = [[NSMutableArray alloc] initWithCapacity:[numberString length]];
NSCharacterSet *decimalSet = [NSCharacterSet decimalDigitCharacterSet];
for (int i = 0; i < [numberString length]; i++) {
unichar character = [numberString characterAtIndex:i];
if (![decimalSet characterIsMember:character]) {
@throw [NSException exceptionWithName:@"Invalid input" reason:@"Non-decimal character" userInfo:nil];
}
NSString *digit = [NSString stringWithFormat:@"%c", character];
[numbers addObject:[NSNumber numberWithInt:[digit intValue]]];
}
_numbers = numbers;
}
return self;
}
- (long)largestProduct:(int)numberOfDigits {
if (numberOfDigits < 0) {
@throw [NSException exceptionWithName:@"Invalid request" reason:@"Negative span" userInfo:nil];
}
int endIndex = (int)[_numbers count] - numberOfDigits;
if (endIndex < 0) {
@throw [NSException exceptionWithName:@"Invalid request" reason:@"Span longer than string length" userInfo:nil];
}
long result = 0;
for (int i = 0; i <= endIndex; i++) {
NSMutableArray *selectedNumbers = [[NSMutableArray alloc] init];
for (int j = i; j < i + numberOfDigits; j++) {
[selectedNumbers addObject:_numbers[j]];
}
long total = 1;
for (NSNumber *selectedNumber in selectedNumbers) {
total *= [selectedNumber intValue];
}
if (total > result) {
result = total;
}
}
return result;
}
@end