- Sqrt(x)
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.
when x = 8
I expected to the function to return 2, since int(y) rounds down the number, but I got a ZeroDivisionError on line (estimate = (1/2)*(estimate+(x/estimate)). This is an easy leetcode problem #69 sqrt(x)
Here is my code which I ran on leetcode:
def mySqrt(self, x):
estimate= 1 + ((x-1)//2)
difference = abs(x-(estimate*estimate))
tolerance = .005
while difference > tolerance:
estimate = (1/2)*(estimate+(x/estimate))
difference = abs((x-(estimate*estimate)))
return int(estimate)`
Runtime Error
ZeroDivisionError: integer division or modulo by zero
estimate = (1/2)*(estimate+(x/estimate))
Line 8 in mySqrt (Solution.py)
ret = Solution().mySqrt(param_1)
Line 29 in _driver (Solution.py)
_driver()
Line 39 in <module> (Solution.py)
Sakher Haris is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.