1年前 (2018-08-15)  编程语言 |   抢沙发  6 
文章评分 0 次,平均分 0.0

The Fibonacci sequence of numbers is 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The first and second numbers are 1 and after that ni = ni-2 + ni-1, e.g., 34 = 13 + 21. A number in the sequence is called a Fibonacci number. Write a method with signature int closestFibonacci(int n) which returns the largest Fibonacci number that is less than or equal to its argument. For example, closestFibonacci(13) returns 8 because 8 is the largest Fibonacci number less than 13 and closestFibonacci(33) returns 21 because 21 is the largest Fibonacci number that is <= 33. closestFibonacci(34) should return 34. If the argument is less than 1 return 0. Your solution must not use recursion because unless you cache the Fibonacci numbers as you find them, the recursive solution recomputes the same Fibonacci number many times.

java 代码实现:

 

package com.zzy;

/**
 * 更多请关注: http://hadoopall.com
 * Created by hadoopall on 14/08/2018.
 */
public class closestFibonacci {

    public static void main(String[] args) {
        System.out.println(closestFibonacci(0));
    }


    public static int closestFibonacci(int n){

        if( n==2 || n == 1 ){
            return 1;

        }else if(n&lt; 1){
            return 0;
        }



        int n1 = 1;
        int n2 = 1;
        int n3 = n1 + n2;

        while (true ){

            n1 = n2;
            n2 = n3;
            n3 = n1 + n2;

            if (n3 &gt;= n ){
                return n2;
            }
        }

    }

    public static int f(int ni , int nj){
        return ni+nj;
    }


}
 

除特别注明外,本站所有文章均为HadoopAll原创,转载请注明出处来自http://hadoopall.com/614.html

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册

扫一扫二维码分享