Skip to content

Latest commit

 

History

History
22 lines (22 loc) · 636 Bytes

69. Sqrt(x).md

File metadata and controls

22 lines (22 loc) · 636 Bytes

思路

求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;  
    }
};