zoukankan      html  css  js  c++  java
  • Fibonacci Number

    Get the Kth number in the Fibonacci Sequence. (K is 0-indexed, the 0th Fibonacci number is 0 and the 1st Fibonacci number is 1).

    Examples

    • 0th fibonacci number is 0
    • 1st fibonacci number is 1
    • 2nd fibonacci number is 1
    • 3rd fibonacci number is 2
    • 6th fibonacci number is 8

    Corner Cases

    • What if K < 0? in this case, we should always return 0.
    • Is it possible the result fibonacci number is overflowed? We can assume it will not be overflowed when we solve this problem on this online judge, but we should also know that it is possible to get an overflowed number, and sometimes we will need to use something like BigInteger.

    time: O(n), space: O(1)

    public class Solution {
      public long fibonacci(int K) {
        // Write your solution here
        if(K <= 1) return K < 0 ? 0 : K;
        long a = 1, b = 1;
        for(int i = 2; i < K; i++) {
          long tmp = a;
          a = a + b;
          b = tmp;
        }
        return a;
      }
    }
  • 相关阅读:
    swift 初见-4运算符与字符串操作
    IOS中数据持久化1-CoreData
    swift 初见-3
    swift 初见-2
    系统硬件1-短信,打电话
    swift 初见-1
    socket理解流程图
    文件操作方法fscanf
    Prim模板
    树剖求LCA模板
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10129612.html
Copyright © 2011-2022 走看看