Wins the offer (10) - Fibonacci number and a hop step problems

to sum up

2 ^ (n-1) shift operation can be carried out: 1 << (n-1)
If the recursion not think, you can find the law, the code is very simple

Fibonacci number (10)

We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0).

n<=39

public class Solution {
    public int Fibonacci(int n) {
        // 先判断n必须在范围内取值
        if(n > 39 && n <= 0) return 0;
        // 为1直接返回
        if(n == 1) return 1;
        
        int a = 0;
        int b = 1;
        int result = 0;
        for(int i = 2;i<=n;i++){
            result = a + b;
            a = b;
            b = result;
        }    
        return result;       
    }
}

Jump stairs (10)

A frog can jump on a Class 1 level, you can also hop on level 2. The frog jumped seeking a total of n grade level how many jumps (the order of different calculation different results).

public class Solution {
    public int JumpFloor(int target) {
        if(target == 1) return 1;
        if(target == 2) return 2;
        int a = 1;
        int b = 2;
        int result = 0;
        for(int i = 3;i<=target;i++){
            result = a + b;
            a = b;
            b = result;
        }
        return result;
    }
}

Abnormal jump stairs

A frog can jump on a Class 1 level, you can also hop on level 2 ...... n It can also jump on stage. The frog jumped seeking a total of n grade level how many jumps.

class Solution {
    public int JumpFloorII(int target) {
        if(target == 1) return 1;
        return (int)Math.pow(2,target-1);
    }
}

public class Solution {
    public int JumpFloorII(int target) {
        if(target == 1) return 1;
       // return (int)Math.pow(2,target-1);
        return 1<<(target -1);
    }
}

Guess you like

Origin www.cnblogs.com/benjieqiang/p/11404019.html