mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 69. Sqrt(x).md
This commit is contained in:
parent
fe4cdf9529
commit
f1ae30a3f0
22
69. Sqrt(x).md
Normal file
22
69. Sqrt(x).md
Normal file
@ -0,0 +1,22 @@
|
||||
# [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/description/)
|
||||
# 思路
|
||||
求int型数的平方根并向下取整。
|
||||
考虑采用二分法。
|
||||
注意:为了防止溢出,判断mid * mid与 x 的值时用除法,即判断 mid 与 x / mid的大小关系。
|
||||
# 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;
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user