[leetcode_69]Sqrt(x)

sqrt模拟。注意两个int乘法可能越界。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
    int sqrt(int x) {
        //x >= 0 0 ~ x/2
        if(x <= 0)return 0;
        int left = 1;
        int right = x / 2;
        bsearch(left, right, x);
        return ans;
    }
private:
    int ans;
    void bsearch(int left, int right, int x) {
        if(left >= right) {
            ans = left;
            if(1.0 * ans * ans > x)
                ans--;
            return;
        }
        int mid = (left + right) / 2;
        if(1.0 * mid * mid == x) {
            ans = mid;
            return;
        }
        else
            if(1.0 * mid * mid > x) {
                bsearch(left, mid-1, x);
            }
            else 
                if(1.0 * mid * mid < x) {
                    bsearch(mid+1, right, x);
                }
    }
};
Licensed under CC BY-NC-SA 4.0