您的位置 首页 编程语言

closestFibonacci

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://huamaodashu.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< 1){
            return 0;
        }



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

        while (true ){

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

            if (n3 >= n ){
                return n2;
            }
        }

    }

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


}

猫叔总结了 适合新手操作的副业 《淘宝虚拟产品月入2万的 6个 细分类目》的电子书 仅供参考

如果你对虚拟产品比较感兴趣,可以点击:

淘宝卖什么虚拟产品赚钱(月入2万+)

hadoopall

关于花猫大叔短视频创业 作者: hadoopall

热门文章

发表评论

电子邮件地址不会被公开。