1. Topic description and requirements
topic description
Given a non-negative integer x, compute and return the arithmetic square root of x.
Since the return type is an integer, only the integer part of the result is kept , and the decimal part will be discarded.
Note: Any built-in exponential functions and operators such as pow(x, 0.5) or x ** 0.5 are not allowed .
example
Example 1:
输入:x = 4
输出:2
Example 2:
输入:x = 8
输出:2
解释:8 的算术平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
hint
0 <= x <= 231 - 1
2. Problem-solving ideas
General idea:
To find the arithmetic square root of x, you can use the binary search method to find the arithmetic square root of x in [1, x/2+1]. Set two subscripts left and right, the reason for right=x/2+1 is that x/2 is removed, so you need to add 1 to it, and then use left<=right as the loop condition, define mid=(left+right )/2, then compare whether mid is equal to x/mid, if it is, it means that the arithmetic square root of x has been found; mid<x/mid means that the arithmetic square root of x should be on the right, so let left=mid+1; if mid >x/mid, that means the arithmetic square root of x should be on the left, so let right=mid-1. Finally return right.
Specific steps:
1. Set the integer variables left and right as subscripts for auxiliary access
2. Use left<=right as the loop, because if left>right means it is empty
3. Determine between mid and x/mid, enter respectively different judgment statements.
4. Return to right.
3. Specific code
int mySqrt(int x){
int left=1,right=x/2+1;
while(left<=right)
{
int mid=(left+right)/2;
if(mid>x/mid)
{
right=mid-1;
}
else if(mid<x/mid)
{
left=mid+1;
}
else
return mid;
}
return right;
}