mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
23 lines
636 B
Markdown
23 lines
636 B
Markdown
# [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;
|
||
}
|
||
};
|
||
```
|