[Swipe the question bank] Sword refers to Offer_ programming questions, the integer power of the value, adjust the order of the array, and cover the matrix

1. The integer power of the value.

Title description

Given a floating-point base of type double and an integer exponent of type int. Find the exponent power of base.

Ensure that base and exponent are not 0 at the same time

 

1. Power operator

function Power(base, exponent)
{
    return base ** exponent;
}

2. Tuning

function Power(base, exponent)
{
    return Math.pow(base, exponent);
}

3. Accumulated multiplication

function Power(base, exponent)
{
    var result = 1.0;
    if(exponent == 0) return 1;
    else if(exponent > 0){
        for(var i = 0 ; i < exponent;i++){
            result *= base;
        }
    }else {
        for(var i = 0 ; i < (0-exponent);i++){
            result *= base;
        }
        result = 1/result;
    }
    return result;
}

Second, adjust the order of the array so that the odd numbers are in front of the even numbers

Title description

Enter an integer array and implement a function to adjust the order of the numbers in the array so that all odd numbers are in the first half of the array, and all even numbers are in the second half of the array, and the relative between odd and odd, even and even is guaranteed The location remains unchanged.

 

Spread operator

function reOrderArray(array)
{
    var even = [];  //定义一个存放偶数的数组
    var odd = [];  //定义一个存放奇数的数组

    for (var i = 0; i < array.length; i++) {
      if(array[i] % 2 == 0) even .push(array[i]);
      else odd.push(array[i]);
    }
    return [...odd,...even ]; 
}

Three, matrix coverage

Title description

We can use 2*1 small rectangles horizontally or vertically to cover larger rectangles. How many ways are there to cover a large 2*n rectangle with n small 2*1 rectangles without overlapping?

Idea: Fibonacci sequence

method one:

function rectCover(number)
{
    if(number == 0) return 0;
    if(number == 1) return 1;
    if(number == 2) return 2;
     
    return rectCover(number - 1)+ rectCover(number - 2);
}

Method Two:

function rectCover(number)
{
    var a = [];
    a[0] = 0;
    a[1] = 1;
    a[2] = 2;
    if(number < 3) return a[number];
    for(var i = 3 ; i <= number ; i++){
        a[i] = a[i - 1]+ a[i - 2];
    }
    return a[number];
}

Method three:

function rectCover(number)
{
    if(number == 0) return 0;
    var a = 0;
    var b = 1;
    while(number-- > 0){
        var t = b;
        b += a;
        a = t;
    }
    return b;
}

 

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/100183073