forked from 12meses12katas/Enero-String-Calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringCalculator.m
66 lines (51 loc) · 1.5 KB
/
StringCalculator.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
64
65
66
//
// StringCalculator.m
// StringCalculator
//
// Created by Roberto Perez Cubero on 29/01/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "StringCalculator.h"
@implementation StringCalculator
- (NSString*) getDelimiterOfString: (NSString*) theString
{
NSString* delimiter = @",";
NSArray *lines = [theString componentsSeparatedByString:@"\n"];
NSString* firstLine = [lines objectAtIndex:0];
if ( [firstLine hasPrefix:@"//"] )
{
delimiter = [firstLine substringFromIndex:2];
}
return delimiter;
}
- (int) add: (NSString*) string
{
if ([string length] == 0) return 0;
NSString* delimiter = [self getDelimiterOfString:string];
int count = 0;
NSArray *lines = [string componentsSeparatedByString:@"\n"];
for (NSString* line in lines)
{
NSArray *numbers = [line componentsSeparatedByString:delimiter];
NSMutableArray *negativeNumbers = [[NSArray alloc] init];
for (NSString* number in numbers)
{
int iNumber = [number intValue];
if ( iNumber < 0 )
[negativeNumbers addObject:number];
if ( iNumber <= 1000 )
count += iNumber;
}
if ([negativeNumbers count] != 0)
{
NSMutableString* exceptionMessage = [NSMutableString stringWithString:@"Negative Numbers not allowed. Found:"];
for ( NSString* i in negativeNumbers )
[exceptionMessage appendFormat:@"%d ", [i intValue]];
@throw [NSException exceptionWithName:@"NegativeNumberException"
reason:exceptionMessage
userInfo:nil];
}
}
return count;
}
@end