Alan Zhan Blog

Live for nothing, or die for something

69. Sqrt(x)

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

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.

 

Constraints:

  • 0 <= x <= 231 - 1

Problem

What is the integer part of the square root of x?

Approach

We use binary search to rapidly narrow the boundaries. By squaring mid, we can determine where the square root falls. The code is short, so I’ll skip the detailed steps.

Source Code

func mySqrt(x int) int {
    left := 1
    right := x
    for left < right {
        mid := (left + right + 1) / 2
        if mid * mid > x {
            right = mid - 1
        } else {
            left = mid
        }
    }
    return right
}

Closing

Do you have a better or simpler solution?

Feel free to leave a comment on my blog. Your feedback motivates me to keep writing. Thank you for reading, and let’s grow together to become better versions of ourselves.