Two interview questions

1. Programming questions

 

1) Please use js to define an Animal class, including the attribute name and the method sleep

2) Please define the Person class, inherit the above class, and add the speak method

 

function Animal() {
    this.name = '';
}

Animal.prototype.sleep = function () { console.log('sleep...'); };


function Person () {}

Person.prototype = new Animal();
Person.prototype.constructor = Person;
Person.prototype.speak = function() { console.log('speak...'); };

 

2. Write a method for finding the square root. The first parameter x is an integer operand, and the second parameter y is also an integer, indicating the allowable error

function mySqrt (x, y) {
    let result;
    ...
    return result;
}

 satisfy

 x - result * result <= y

Please complete the function (do not use Math.sqrt())

 

function mySqrt (x, y) {
    let result;
    let start = 0, end = x, mid;

    while(true) {
        mid = (start + end) / 2;
        if (Math.abs(x - mid * mid) <= y) {
            result = mid;
            break;
        }
        if (x > mid * mid) {
            start = mid;
        }
        if (x < mid * mid) {
            end = mid;
        }

    }
    return result;
}
mySqrt( 100, 0.01 );

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326385914&siteId=291194637