69. Sqrt(x)


Problem

https://leetcode.com/problems/sqrtx/

Implement int sqrt(int x).

Compute and return the square root of x.

Solution

Binary search.

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    let i = 0
    let j = Math.floor(x / 2) + 1

    while (i <= j) {
        let mid = Math.floor((i + j) / 2)
        let pow = mid * mid
        if (pow === x) {
            return mid
        } else if (pow < x) {
            i = mid + 1
        } else {
            j = mid - 1
        }
    }

    return j
};

results matching ""

    No results matching ""