斐波那契数列-爬楼梯-大数问题

在你面前有一个n阶的楼梯,你一步只能上1阶或2阶。
请问计算出你可以采用多少种不同的方式爬完这个楼梯。

这个问题乍一看就是简单的斐波那契数列问题,但是当楼梯数量到达一定数量后,例如 39,此时基本数据类型 int 或 long 都会溢出。所以需要解决大数的问题。

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int target = sc.nextInt();
        int[] list = { 0, 1, 2 };
        if (target < 3) {
            System.out.println(list[target]);
            return;
        }
        String jumpNOne = "2";// 最后只跳一步
        String jumpNTwo = "1";// 最后跳两步
        String jumpN = "0";// 统计跳 target 个台阶的方案
        for (int i = 3; i <= target; i++) {
            jumpN = bigData(jumpNTwo, jumpNOne);
            jumpNTwo = jumpNOne;
            jumpNOne = jumpN;
        }
        System.out.println(jumpN);
    }

   大数问题:

// s2 >= s1  
public static String bigData(String s1, String s2) { String result = "";// 记录相加结果 int flag = 0;// 记录是否有进位 int i = s1.length() - 1;// 记录s1 的最后一位,也就是个位数 int j = s2.length() - 1;// 记录s2 的最后一位,也就是个位数 int temp = 0; while (i >= 0 || j >= 0) { // s2 一定比 s1 大,所以可能存在 s2 比 s1 多一位 if (i < 0) {// temp = s2.charAt(j) - '0' + flag; result = new Integer(temp).toString() + result; flag = 0; } else { temp = (s1.charAt(i) - '0') + (s2.charAt(j) - '0') + flag; flag = temp / 10; temp = temp % 10; result = new Integer(temp).toString() + result; } i--; j--; } if(flag == 1) result = "1" + result; return result; }

猜你喜欢

转载自www.cnblogs.com/lyw-hunnu/p/12766201.html