题目:
image.png
解答:
#import <Foundation/Foundation.h>
NSInteger fibonacci(NSInteger n) {
if (n < 0) {
return 0;
}
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
NSInteger preSecondCount = 0;
NSInteger preFirstCount = 1;
NSInteger currentCount = 0;
for (NSInteger tmpIndex = 1; tmpIndex < n; tmpIndex++) {
currentCount = preFirstCount + preSecondCount;
preSecondCount = preFirstCount;
preFirstCount = currentCount;
}
return currentCount;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"%ld", fibonacci(2));
NSLog(@"%ld", fibonacci(3));
NSLog(@"%ld", fibonacci(4));
NSLog(@"%ld", fibonacci(5));
NSLog(@"%ld", fibonacci(8));
}
return 0;
}
网友评论