Find the missing term in an Arithmetic Progression

2017/12/26 posted in  codeWars

#import <Foundation/Foundation.h>

NSNumber *findMissing(NSArray *list) {
    int len = [list count];
    int n = len+1;
    int d1 = [list[1] intValue]-[list[0] intValue];
    int d2 = [list[len-1] intValue]-[list[len-2] intValue];
    int d = 0;
    if (d1<0) {
        d = d1>d2?d1:d2;
    }else{
        d = d1<d2?d1:d2;
    }
    if (n == 3) {
        return @(([[list firstObject] intValue]+[[list lastObject] intValue])/2);
    }
    int num = [[list firstObject] intValue];
    for (int i = 0;i<len;i++) {
        if ([list[i] intValue]!=num) {
            return @(num);
        }
        num+=d;
    }
    
    return @(0);
}