Sqrt(x) Leetcode Solution

In this post, we are going to solve the Sqrt(x) Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

Sqrt(x) Leetcode Solution
Sqrt(x) Leetcode Solution

Problem

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 builtin 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

Now, lets see the leetcode solution of Text Justification Leetcode Solution.

Sqrt(x) Leetcode Solution in Python

class Solution:
  def mySqrt(self, x: int) -> int:
    l = 1
    r = x + 1

    while l < r:
      m = (l + r) // 2
      if m * m > x:
        r = m
      else:
        l = m + 1

    # L: smallest number s.t. l * l > x
    return l - 1

Sqrt(x) Leetcode Solution in CPP

class Solution {
 public:
  int mySqrt(int x) {
    unsigned l = 1;
    unsigned r = x + 1u;

    while (l < r) {
      const unsigned m = (l + r) / 2;
      if (m > x / m)
        r = m;
      else
        l = m + 1;
    }

    // L: smallest number s.t. l * l > x
    return l - 1;
  }
};

Sqrt(x) Leetcode Solution in Java

class Solution {
  public int mySqrt(long x) {
    long l = 1;
    long r = x + 1;

    while (l < r) {
      final long m = (l + r) / 2;
      if (m > x / m)
        r = m;
      else
        l = m + 1;
    }

    // L: smallest number s.t. l * l > x
    return (int) l - 1;
  }
}

Note: This problem Sqrt(x) is generated by Leetcode but the solution is provided by Chase2learn This tutorial is only for Educational and Learning purposes.

NEXT: Climbing Stairs Leetcode Solution

Sharing Is Caring