Sqrt(x) | LeetCode 69

[Written explanation will be added soon]

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard


Here is the full implementation.

/**
 * @param {number} x
 * @return {number}
 */
let mySqrt = function(num) {	
  if (num < 2) {
    return num;
  }

  let left = 1;
  let right = num;

  while (left < right) {
    let mid = left + Math.floor((right - left) / 2);

    if (mid * mid === num) {
      return mid;
    } else if (mid * mid > num) {
      right = mid;
    } else if (mid * mid < num) {
      left = mid + 1;
    }
  }

  return left - 1;
};