I have been trying the question on hacker rank in which addition of all the substring of a string is taken into account. In doing so our answer exceeds the limit of NSInteger, NSUInteger, long, very very long, double.
So in this case i tried
- (NSDecimalNumber *) substrings:(NSString *)n {
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([n rangeOfCharacterFromSet:notDigits].location == NSNotFound) {
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSDecimalNumber *sum = [NSDecimalNumber decimalNumberWithString:@"0"];
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i<n.length; i++) {
for (NSInteger j = 1; j<=n.length-i; j++) {
NSString *stringInRange = [n substringWithRange:NSMakeRange(i, j)];
[arr addObject:stringInRange];
NSDecimalNumber *myNumber1 = [NSDecimalNumber decimalNumberWithString:stringInRange];
sum = [sum decimalNumberByAdding:myNumber1];
}
}
return sum;
} else {
return nil;
}
}
But still, I am getting the wrong answer of addition. I want to know in such cases where test cases include much heavier value than the limits, what API should we use to perform arithmetic operation?
What I have tried is a correct approach or not?