洛谷 P1255 数楼梯 Java

高精度、递推,斐波那契
在使用BigInteger的时候,导入java.math.*

import java.math.BigInteger;
import java.util.*;
class test{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        BigInteger f[] = new BigInteger[n+1];
        f[0] = BigInteger.ZERO;
        if (n >= 1)
        {
        //添加n对1和0的判断,因为数组定义的大小是n+1,如果输入 0 的话,对f[1]赋值会数组越界。
            f[1] = BigInteger.ONE;
        }
        if (n >= 2)
        {
            f[2] = BigInteger.valueOf(2);
            for (int i = 3 ; i <= n ; i++)
            {
                f[i] = f[i-1].add(f[i-2]);
            }
        }
        System.out.println(f[n]);

    }
}

猜你喜欢

转载自blog.csdn.net/qq_45260619/article/details/105514040
今日推荐