Skip to content

Commit d0c6f90

Browse files
authored
Merge pull request halfrost#146 from hanlins/69/sqrtx/consise-binary-search
Make the binary search solution more concise for Sqrt x
2 parents 295504e + 60d3b04 commit d0c6f90

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

leetcode/0069.Sqrtx/69. Sqrt(x).go

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,18 @@
11
package leetcode
22

3-
// 解法一 二分
3+
// 解法一 二分, 找到最后一个满足 n^2 <= x 的整数n
44
func mySqrt(x int) int {
5-
if x == 0 {
6-
return 0
7-
}
8-
left, right, res := 1, x, 0
9-
for left <= right {
10-
mid := left + ((right - left) >> 1)
11-
if mid < x/mid {
12-
left = mid + 1
13-
res = mid
14-
} else if mid == x/mid {
15-
return mid
5+
l, r := 0, x
6+
for l < r {
7+
mid := (l + r + 1) / 2
8+
if mid*mid > x {
9+
r = mid - 1
1610
} else {
17-
right = mid - 1
11+
l = mid
1812
}
1913
}
20-
return res
14+
15+
return l
2116
}
2217

2318
// 解法二 牛顿迭代法 https://en.wikipedia.org/wiki/Integer_square_root

0 commit comments

Comments
 (0)