[Java][BinarySearch][LeetCode] Sqrt(x) #69

SP Hou
1 min readDec 16, 2021

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 built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

Example 1:

Input: x = 4
Output: 2

=====================================

I got mid value from left and right side.
we know that :
square =value*value
=> value = square/value
if value equal mid value, it is mean we got the square root.
if mid>value, it is mean, right side is too large, we should fix to mid-1,
if mid<value, it is mean, left side is to small, we should fix to mid+1,
until we find value equal mid value.

從兩邊邊界(l and r)往目標值集中,
每次都取邊界的中間值(mid),
square=value*value
=>value = square/value,
為了知道是不是已經到了整數的平方根,
將x除每次的mid,
得到的值(ava),如果等於mid,表示找到整數平方根,
mid>ava,則表示右邊邊界需要縮小到mid-1,
mid<ava,則表示左邊邊界需要增加到mid+1,
以此逐漸逼近,直到找到整數平方根。

--

--