LeetCode face questions 10- I. Fibonacci number

Here Insert Picture Description
To be noted that a% k + b% k = (a + b)% k
This question will be on the inside of the modulo k, otherwise it will overflow

class Solution {
    public int fib(int n) {
        if(n <= 0){
            return 0;
        }
        if(n == 1){
            return 1;
        }
        long sum = 0;
        long pre = 1,ppre = 0;
        for(int i = 2;i <= n;i++){
            sum = (pre + ppre)%1000000007;
            ppre = pre;
            pre = sum;
        }
        return (int)sum;
    }
}
Published 169 original articles · won praise 5 · Views 7671

Guess you like

Origin blog.csdn.net/fsdgfsf/article/details/104719541