Sqrt(x) LeetCode Solution

Last updated on October 25th, 2024 at 10:26 pm

Here, We see Sqrt(x) LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Binary Search, Math

Companies

Apple, Bloomberg, Facebook

Level of Question

Easy

Sqrt(x) LeetCode Solution

Sqrt(x) LeetCode Solution

Problem Statement

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.

1. Sqrt(x) Leetcode Solution C++

class Solution {
public:
    int mySqrt(int x) {
        long long s=0,e=INT_MAX,ans=0;
        while(s<=e){
            long long m=s+(e-s)/2;
            if(m*m<=x){
                ans=m;
                s=m+1;
            }
            else e=m-1;
        }
        return ans;        
    }
};

2. Sqrt(x) Leetcode Solution Java

class Solution {
    public int mySqrt(int x) {
    long r = x;
    while (r*r > x)
        r = (r + x/r) / 2;
    return (int) r;        
    }
}

3. Sqrt(x) Leetcode Solution JavaScript

var mySqrt = function(x) {
    r = x;
    while (r*r > x)
        r = ((r + x/r) / 2) | 0;
    return r;    
};

4. Sqrt(x) Solution Python

class Solution(object):
    def mySqrt(self, x):
        r = x
        while r*r > x:
            r = (r + x/r) / 2
        return r
Scroll to Top