美文网首页iOS 剑指offer
【剑指Offer学习】【面试题9 : 斐波那契数列】

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

作者: 果哥爸 | 来源:发表于2018-01-30 17:00 被阅读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;
    }
    

    相关文章

      网友评论

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

        本文链接:https://www.haomeiwen.com/subject/jhjiaxtx.html