Computing the integer square root of a number using Binary Search.
The original problem is here.
Instead of an array, our search space is the range of possible integer answers from $1$ up to $x$.
left = 1 and right = x.mid = left + (right - left) // 2.mid * mid with x: mid * mid == x, we’ve found the exact integer root! Return mid.mid * mid > x, mid is too large to be the square root. We tighten the upper bound: right = mid - 1.mid * mid < x, the square root could be mid or something larger. We tighten the lower bound: left = mid + 1. It’s okay to discard mid even if it’s the answer. The reason is written at termination. mid, the loop stops when the pointers cross (left > right).mid=left=right.left will be increased and the algorithm terminates. right is the answer.right will be decreased by one and the algorithm terminates. right is the answer.class Solution:
def mySqrt(self, x: int) -> int:
left = 0
right = x
while left <= right:
mid = (left+right)//2
mid_sq = mid*mid
if mid_sq == x:
return mid
if mid_sq > x:
right = mid - 1
if mid_sq < x:
left = mid+1
return right
left, right, and mid) indicating indices.