Leetcode 69. Sqrt(x)

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Sqrt(http://noahsnail.com/images/leetcode/Sqrt(x).jpeg)

2. Solution

  • Binary Search
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int mySqrt(int x) {
int left = 0;
int right = x;
while(left <= right) {
long mid = (left + right) / 2;
long square = mid * mid;
if(square == x) {
return mid;
}
if(square > x) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
return right;
}
};
  • Newton’s Method
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int mySqrt(int x) {
long y = x;
while(y * y > x) {
y = (y + x / y) / 2;
}
return y;
}
};

Reference

  1. https://leetcode.com/problems/sqrtx/description/
如果有收获,可以请我喝杯咖啡!