Journal Archive

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    // base case
    if (x === 1) return 1;
    let left = 0;
    let right = x;
    // start binary search
    while (left <= right) {
        let mid = Math.floor( (right + left) / 2);
        const LB = mid * mid;
        const UB = (mid + 1) * (mid + 1)
        if (LB <= x && x < UB) {
            return mid;
        } else if (x < LB) {
            right = mid;
        } else {
            left = mid;
        }
        
    }
};

Day 35: Solving one of LeetCode problems

69. Sqrt(x) Difficulty - Easy

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

 

Example 1:

Input: x = 4
Output: 2
        

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.