Leetcode Problem 69. Sqrt(x)

69. Sqrt(x)

Leetcode Solutions

Approach: Binary Search

  1. If x is less than 2, return x as the square root is either x itself or 0.
  2. Set the left boundary left to 2 and the right boundary right to x / 2.
  3. While left is less than or equal to right: a. Calculate the guess num as the average of left and right (integer division). b. If num * num is greater than x, set right to num - 1. c. If num * num is less than x, set left to num + 1. d. If num * num equals x, return num as the square root.
  4. If the loop ends without finding an exact square root, return right as the integer square root of x.
UML Thumbnail

Approach: Recursion + Bit Shifts

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...