題目:
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:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since
the decimal part is truncated, 2 is returned.
問題解析:
求給定整數x的平方根。
鏈接:
思路標籤:
算法:二分法
解答:
1. 二分法
- 使用二分法在
1~x
的範圍內進行查找; - 雖然題目簡單,但是需要注意的邊界範圍,以及mid的賦值方式需要考慮;
class Solution {
public:
int mySqrt(int x) {
if (0 == x) return 0;
int left = 1, right = x, ans;
while (left <= right) {
int mid = left + (right - left) / 2; //mid爲在原來的基礎上+一半
if (mid <= x / mid) {
left = mid + 1;
ans = mid;
} else {
right = mid - 1;
}
}
return ans;
}
};
2. 牛頓法
- 直接利用牛頓法求解。
- 具體解釋自行Google。
class Solution {
public:
int mySqrt(int x) {
long r = x;
while (r*r > x)
r = (r + x/r) / 2;
return r;
}
};