iOS 剑指offer

【剑指Offer学习】【面试题9 : 斐波那契数列】

2018-01-30  本文已影响20人  果哥爸

题目:

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;
}
上一篇下一篇

猜你喜欢

热点阅读