Leetcode: Sqrt(x)
2014-09-17 13:24
351 查看
Implement
Compute and return the square root of x.
思路:二分法。在[0, x/2+1]这个范围内二分就可以。注意要使用long long type,否则当数据过大容易出现溢出。
class Solution {
public:
int sqrt(int x) {
long long start = 0;
long long end = x / 2 + 1;
while (start <= end) {
long long mid = start + (end - start) / 2;
if (x == mid * mid){
return mid;
} else if (x > mid * mid) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return end;
}
};
int sqrt(int x).
Compute and return the square root of x.
思路:二分法。在[0, x/2+1]这个范围内二分就可以。注意要使用long long type,否则当数据过大容易出现溢出。
class Solution {
public:
int sqrt(int x) {
long long start = 0;
long long end = x / 2 + 1;
while (start <= end) {
long long mid = start + (end - start) / 2;
if (x == mid * mid){
return mid;
} else if (x > mid * mid) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return end;
}
};
相关文章推荐
- [leetcode] 69. Sqrt(x)
- leetcode-Sqrt(x) (2014.4.7)
- 【leetcode】69. Sqrt(x)【M】【74】
- leetcode 第69题 Sqrt(x)
- [leetcode] Sqrt(x)
- [LeetCode]69. Sqrt(x)
- leetcode 69 Sqrt(x)
- LeetCode_Sqrt
- 【小熊刷题】sqrt(x) <Leetcode 69 Java>
- [leetcode]Sqrt(x)
- Leetcode134: Sqrt(x)
- Leetcode 50. Pow(x, n) & 69. Sqrt(x)
- LeetCode【69】 Sqrt(x)
- LeetCode 69. Sqrt(x)
- LeetCode Sqrt
- [Leetcode]@python 69. Sqrt(x)
- 69. Sqrt(x) LeetCode
- 刷leetcode:Sqrt(x)
- LeetCode:Sqrt(x)
- [leetcode]Sqrt(x) @ Python