我试图从 Project Euler 解决问题 22,使用以下代码:
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",partSum);
}
NSLog(@"%@ - %lli",str,partSum);
sum += [namesArray indexOfObject:str]*partSum;
}
NSLog(@"%lli",sum);
将名称获取到数组没有问题,但是当我记录sum
和partSum
变量时,我会得到奇怪的值,例如-9223372036854775755
. 据我所知,这是由于溢出,但是当程序计算示例中的名称时,我得到以下输出:
-9223372036854775808
-9223372036854775805
-9223372036854775790
-9223372036854775778
-9223372036854775769
-9223372036854775755
53
"COLIN" - 53
然后第一个值溢出,但最后一个结果奇怪地正确(并非所有名称都如此)。为什么会有这样的溢出?这些数字应该只是 3、18、30、39、53。猜测是程序也会处理"
字符并在alphabet
. 为此,我在网上看了很多,找不到如何从字符串中删除它们。我不能只使用[str stringByReplacingOccurrencesOfString:@""" withString:@""]
. 有什么建议么?