0

私は長い加算のように機能する add メソッドを作成しようとしているので、最後から加算を開始し、キャリーを正しく取得できるように逆方向に作業したいと考えています。配列。たとえば、私がやろうとしていること。文字 123456789 の 2 つの配列があり、それらを 9 + 9 から始めて追加し、次に 8 + 8 に移動したい

したがって、配列を逆方向に反復する正しい方法を使用していると確信していますが、試行するたびに実行時エラー、範囲外のインデックスが発生し、その理由がわかりません。どんな助けでも素晴らしいでしょう、なぜそれが例外をスローし続けるのか分かりません。

-(MPInteger *) add: (MPInteger *) x
{

    NSMutableArray *a = self->intString;
    NSMutableArray *b = x->intString;
    NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];



    //for (int i  = 0; i < [a count]; i++) {
    for (NSInteger i = [a count] - 1; i > 0; i--) {
        int num = 10;
        NSNumber *ourNum = [NSNumber numberWithInt:num];
        NSNumber *total = [NSNumber numberWithInt:[[a objectAtIndex:i] intValue] + [[b objectAtIndex:i] intValue]];
        if ([total intValue] >= [ourNum intValue]) {
            total = [NSNumber numberWithInt:([total intValue] - [ourNum intValue])];
            [c addObject:[NSNumber numberWithInt:([total intValue])]];
        } else {
            [c addObject:[NSNumber numberWithInt:[[a objectAtIndex:i] intValue]+[[b objectAtIndex:i] intValue]]];
        }
        NSLog(@"%@", c[i]);
    }

    return x;
}
4

2 に答える 2

4

まず、このコードをクリーンアップしましょう。

- (MPInteger *)add:(MPInteger *)x {
    NSMutableArray *a = self->intString;
    NSMutableArray *b = x->intString;
    NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];

    for (NSInteger i = [a count] - 1; i > 0; i--) {
        int num = 10;
        NSNumber *ourNum = @(num);
        NSNumber *total = @([a[i] intValue] + [b[i] intValue]);

        if ([total intValue] >= [ourNum intValue]) {
            total = @([total intValue] - [ourNum intValue]);
            [c addObject:@([total intValue])];
        } else {
            [c addObject:@([a[i] intValue] + [b[i] intValue])];
        }

        NSLog(@"%@", c[i]);
    }

    return x;
}

次に、冗長/重複コードを削除しましょう。

- (MPInteger *)add:(MPInteger *)x {
    NSMutableArray *a = self->intString;
    NSMutableArray *b = x->intString;
    NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];

    for (NSInteger i = [a count] - 1; i > 0; i--) {
        int num = 10;
        NSNumber *total = @([a[i] intValue] + [b[i] intValue]);

        if ([total intValue] >= num) {
            total = @([total intValue] - num);
        }

        [c addObject:total];

        NSLog(@"%@", c[i]);
    }

    return x;
}

今、私たちはすべての問題を明確に見ることができます。

  1. から に行き[a count] - 1ます1。0まで行くはずです。
  2. abのサイズが異なる場合があるため、 のみを行う[a count] - 10、たとえば[b count] < [a count]の場合、 にアクセスしようとすると、範囲外のインデックス エラーが発生しますb[i]
  3. の最後に何かを追加していますが、逆方向に反復してcいるため、の最初に追加する必要があります。c
  4. キャリーをどこにも保管しません。
  5. c[i]存在しないにアクセスしています。
于 2013-08-28T21:25:45.267 に答える
0

あなたは空の配列 'c' から始めており、NSLog c[i] は最初の反復で明らかに範囲外です。

于 2013-08-28T21:23:52.350 に答える