Exceeding Strange - Objective-C


I was trying to solve the problem 22 from Project Euler, with the following code :

        NSArray *alphabet = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];
    NSError *error = nil;

    NSString *file  = [[NSBundle mainBundle] pathForResource:@"names" ofType:@"txt"];
    NSString *names = [[NSString alloc] initWithContentsOfFile: file
                                                      encoding: NSASCIIStringEncoding
                                                         error: &error];

    if (names == nil) {
        [NSException raise:@"Error reading file :" format:@"%@",error];
    NSMutableArray *namesArray = [NSMutableArray arrayWithArray:[names componentsSeparatedByString:@","]];
    unsigned long long int sum = 0;
    unsigned long long int partSum = 0;
    for (NSString *str in namesArray){
        partSum = 0;
        for (int i = 0; i < [str length]; i++) {
            partSum += [alphabet indexOfObject:[NSString stringWithFormat:@"%c",[str characterAtIndex:i]]]+1;
        NSLog(@"%@ - %lli",str,partSum);
        sum += [namesArray indexOfObject:str]*partSum;

There are no problems about getting the names to the array but when I log the sum and partSum variables I get strange values like -9223372036854775755. As far as I know, this due to an overflow, but looking when the program computes the name on the example, I get the following output :

"COLIN" - 53

The first values are then overflowed but the last result is strangely correct (not the case for all names). Why such an overflow? The numbers should be just 3, 18, 30, 39, 53. A guess would be that the program treats also the " characters and looks for the index in alphabet. For that, I look a lot on the net, couldn't find how to delete them from the string. I can't just use [str stringByReplacingOccurrencesOfString:@""" withString:@""]. Any suggestions?

Your guess is right. At the point at which you look for the " then indexOfObject returns NSNotFound, which is a constant with the value MAXINT. Then as @rmaddy pointed out, your NSLog is trying to print that unigned value as a signed one, and you end up with a big negative number.

For removing the " try

[str stringByReplacingOccurrencesOfString:@"\"" withString:@""];