LeetCode/solutions/69. Sqrt(x).md

23 lines
636 B
Markdown
Raw Normal View History

2018-09-28 06:59:29 +00:00
# [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/description/)
# 思路
求int型数的平方根并向下取整。
考虑采用二分法。
注意为了防止溢出判断mid * mid与 x 的值时用除法,即判断 mid 与 x / mid的大小关系。
# C++
2019-09-13 15:08:41 +00:00
``` C++
2018-09-28 06:59:29 +00:00
class Solution {
public:
int mySqrt(int x) {
if(x < 2) return x;
int low = 1, high = x / 2, mid;
while(low <= high){
mid = (low + high) / 2;
if(mid == x / mid) return mid;
else if(mid < x / mid) low = mid + 1;
else high = mid - 1;
}
return high;
}
};
```