zoukankan      html  css  js  c++  java
  • 雷:面试时被问到fibonacci

    1 1 2 3 5 8...

    递归:

    代码
            static int FibonacciRecursive(int n)
            {        
                
    if (n == 1 || n == 2)
                    
    return 1;
                
    else if (n >= 2)
                {
                    
    return FibonacciRecursive(n - 1+ FibonacciRecursive(n - 2);
                }
                
    else if (n <= 0)
                {
                    
    throw new ArgumentNullException(string.Format("{0} is illegal", n));              
                }
                
    return 0;
            }

    非递归:

    代码
            static int Fibonacci(int n)
            {
                
    int lastNumber=1;
                
    int secondNumber=1;
                
    int currentNumber = 1;
                
    if (n > 0)
                {
                    
    for (int i = 3; i <= n; i++)
                    {                   
                        currentNumber 
    = lastNumber+secondNumber;
                        secondNumber 
    = lastNumber;
                        lastNumber 
    = currentNumber;
                    }
                }
                
    else
                {
                    
    throw new ArgumentNullException(string.Format ("{0} is not a legal number",n));
                }
                
    return currentNumber;
            }
  • 相关阅读:
    nullptr和NULL
    tmux用于恢复远程屏幕
    如何改变git的默认路径
    scp拷贝文件
    C++头文件<bits/stdc++.h>
    MAME模拟器使用简单教程
    typescript接口扩展
    Typescript中的可索引接口 类类型接口
    typescript函数类型接口
    typescript静态属性 静态方法 抽象类 多态
  • 原文地址:https://www.cnblogs.com/qixue/p/1669632.html
Copyright © 2011-2022 走看看