Fork me on GitHub

leetcode——[069]Sqrt(x)X的平方根

题目

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 x 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

示例 1:

1
2
输入: 4
输出: 2

示例 2:

1
2
3
4
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

1
2
Input: 4
Output: 2

Example 2:

1
2
3
4
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.

解题方法

二分法,取$0$为起点,$x$为终点,每次循环判断中点值$mid$的平方与$x$的大小,$mid^2<= x$,则起点$left+1$;否则终点$right-1$,直到$left>right$。值得注意的是取中点值时用int mid = left + (right - left) / 2防止$int$型数据溢出,如果用int mid = (left + right) / 2left + right >= 2^32时越界。这段代码跑了6ms,超过了97.63%的Java提交。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
// Method 1 6ms 97.63%
public int mySqrt(int x) {
if (x == 0 || x == 1) {
return x;
}
int ans = 0, left = 0, right = x;
while(left <= right) {
int mid = left + (right - left) / 2;
if (mid <= x / mid) {
left = mid + 1;
ans = mid;
} else {
right = mid - 1;
}
}
return ans;
}
}
BJTU-HXS wechat
海内存知己,天涯若比邻。