LeetCode/solutions/69. Sqrt(x).md
2019-09-13 23:08:41 +08:00

23 lines
636 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/description/)
# 思路
求int型数的平方根并向下取整。
考虑采用二分法。
注意为了防止溢出判断mid * mid与 x 的值时用除法,即判断 mid 与 x / mid的大小关系。
# C++
``` C++
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;
}
};
```