LeetCode 0069. Sqrt(x) Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0069. Sqrt(x)

Description

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

 

Example 1:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

 

Constraints:

  • 0 <= x <= 231 - 1

Solutions

Solution 1: Binary Search

We define the left boundary of the binary search as l = 0 and the right boundary as r = x, then we search for the square root within the range [l, r].

In each step of the search, we find the middle value mid = (l + r + 1) / 2. If mid > x / mid, it means the square root is within the range [l, mid - 1], so we set r = mid - 1. Otherwise, it means the square root is within the range [mid, r], so we set l = mid.

After the search ends, we return l.

The time complexity is O(log x), and the space complexity is O(1).

PythonJavaC++GoRustJavaScriptC#
class Solution: def mySqrt(self, x: int) -> int: l, r = 0, x while l < r: mid = (l + r + 1) >> 1 if mid > x // mid: r = mid - 1 else: l = mid return l(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !