值超过目标c

时间:2018-08-15 07:41:36

标签: ios objective-c nsnumber nsinteger nsdecimalnumber

我一直在尝试关于黑客等级的问题,其中考虑了字符串的所有子字符串的加法。 这样做,我们的答案超出了NSInteger,NSUInteger,长,非常长,两倍的限制。

所以在这种情况下,我尝试了

- (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;
    }
}

但是,我仍然得到加法的错误答案。我想知道在这种情况下,测试用例包含的值比限制值大得多,我们应该使用哪种API来执行算术运算?

我尝试过的方法是否正确?

1 个答案:

答案 0 :(得分:0)

如果需要在Objective-C中使用大整数值进行运算,则可以使用JKBigInteger。例如,您可以将2个大整数相乘,然后使用JKBigInteger将结果转换为NSString。在这里,您可以了解如何使用该库:

JKBigInteger *bigInteger1 = [[JKBigInteger alloc] initWithString:@"2"];
JKBigInteger *bigInteger2 = [[JKBigInteger alloc] initWithString:@"3"];
JKBigInteger* bigInteger3 = [bigInteger1 add:bigInteger2];
NSLog(@"%@", [bigInteger3 stringValue]); // output is 5

我想您可以使用此功能获得所需的值:

-(JKBigInteger*)sumOfSubValues:(JKBigInteger*)value {
    JKBigInteger* currentValue = [[JKBigInteger alloc] initWithString:value.stringValue];
    JKBigInteger* result = [[JKBigInteger alloc] initWithString:currentValue.stringValue];
    NSUInteger digitsCount = currentValue.stringValue.length - 1;
    JKBigInteger* const tenValue = [[JKBigInteger alloc] initWithString:@"10"];
    while (digitsCount != 0) {
        JKBigInteger* const firstDigit = [[JKBigInteger alloc] initWithString:[currentValue.stringValue substringToIndex:1]];
        JKBigInteger* const firstDigitPowerBase = [tenValue pow:(unsigned int)digitsCount];
        JKBigInteger* const firstDigitPower = [firstDigit multiply:firstDigitPowerBase];
        JKBigInteger* const diff = [currentValue subtract:firstDigitPower];
        currentValue = diff;
        digitsCount--;
        result = [result add:currentValue];
    }
    return result;
}

您可以使用以下代码段对其进行测试:

JKBigInteger* result = [self sumOfSubValues:[[JKBigInteger alloc] initWithString:@"1234"]];
NSLog(@"%@", result.stringValue); // output is "1506" (1234 + 234 + 34 + 4)