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
![Sqrt(x) LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Sqrt(x) LeetCode Solution
Table of Contents
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++ orx ** 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.
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;
}
};
Code language: PHP (php)
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;
}
}
Code language: PHP (php)
Sqrt(x) Leetcode Solution JavaScript
var mySqrt = function(x) {
r = x;
while (r*r > x)
r = ((r + x/r) / 2) | 0;
return r;
};
Code language: JavaScript (javascript)
Sqrt(x) Solution Python
class Solution(object):
def mySqrt(self, x):
r = x
while r*r > x:
r = (r + x/r) / 2
return r