comments | difficulty | edit_url |
---|---|---|
true |
简单 |
写一个函数,输入 n
,求斐波那契(Fibonacci)数列的第 n
项(即 F(N)
)。斐波那契数列的定义如下:
F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
示例 1:
输入:n = 2 输出:1
示例 2:
输入:n = 5 输出:5
提示:
0 <= n <= 100
我们定义初始项
时间复杂度
class Solution:
def fib(self, n: int) -> int:
a, b = 0, 1
for _ in range(n):
a, b = b, (a + b) % 1000000007
return a
class Solution {
public int fib(int n) {
int a = 0, b = 1;
while (n-- > 0) {
int c = (a + b) % 1000000007;
a = b;
b = c;
}
return a;
}
}
class Solution {
public:
int fib(int n) {
int a = 0, b = 1;
while (n--) {
int c = (a + b) % 1000000007;
a = b;
b = c;
}
return a;
}
};
func fib(n int) int {
a, b := 0, 1
for i := 0; i < n; i++ {
a, b = b, (a+b)%1000000007
}
return a
}
function fib(n: number): number {
let a: number = 0,
b: number = 1;
for (let i: number = 0; i < n; i++) {
let c: number = (a + b) % 1000000007;
[a, b] = [b, c];
}
return a;
}
impl Solution {
pub fn fib(n: i32) -> i32 {
let mut tup = (0, 1);
for _ in 0..n {
tup = (tup.1, (tup.0 + tup.1) % 1000000007);
}
return tup.0;
}
}
/**
* @param {number} n
* @return {number}
*/
var fib = function (n) {
let a = 0;
let b = 1;
while (n--) {
[a, b] = [b, (a + b) % (1e9 + 7)];
}
return a;
};
public class Solution {
public int Fib(int n) {
int a = 0, b = 1, tmp;
for (int i = 0; i < n; i++) {
tmp = a;
a = b;
b = (tmp + b) % 1000000007;
}
return a % 1000000007;
}
}
class Solution {
func fib(_ n: Int) -> Int {
var a = 0
var b = 1
var count = n
while count > 0 {
let c = (a + b) % 1000000007
a = b
b = c
count -= 1
}
return a
}
}