Created
April 25, 2019 16:47
-
-
Save necusjz/e4adb29942c20eb30575d2812c30e149 to your computer and use it in GitHub Desktop.
面试题 10:斐波那契数列
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
long long Fibonacci(unsigned int n) { | |
if(n <= 0) { | |
return 0; | |
} | |
if(n == 1) { | |
return 1; | |
} | |
return Fibonacci(n-1) + Fibonacci(n-2); | |
} | |
long long Fibonacci(unsigned int n) { | |
int result[2] = {0, 1}; | |
if(n < 2) { | |
return result[n]; | |
} | |
long long fibNMinusOne = 1; | |
long long fibNMinusTwo = 0; | |
long long fibN = 0; | |
for(unsigned int i = 2; i <= n; ++i) { | |
fibN = fibNMinusOne + fibNMinusTwo; | |
fibNMinusTwo = fibNMinusOne; | |
fibNMinusOne = fibN; | |
} | |
return fibN; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment