Sqrt(x) Leetcode Solution

In this post, you will know how 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 Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Leetcode by yourself. If you find any difficulty after trying several times, then you can look for solutions.

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

Sqrt(x) Leetcode Solutions 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 Solutions 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 Solutions 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 BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Same Tree Leetcode Solution

Leave a Reply

Your email address will not be published. Required fields are marked *