Leetcode第69题 x 的平方根 C++(未完善)

令人头疼的二分法,还是无法信手拈来
看看我第一次的错误示范

class Solution {
public:
    int mySqrt(int x) {
        int low=0,high=x,medium;
        int temp,result;
        while(low<=high)
        {
            medium=(low+high)/2;
            temp=medium*medium;
            if(temp==x)
            return medium;
            else if (temp<x)
            low=medium+1;
            else 
            high=medium-1;
        }
        return low*low<=x?low:low-1;        
    }
};

最终结果这样:

class Solution {
public:
    int mySqrt(int x) {
        long low=0,high=x,medium;
        long temp;
        while(low<=high)
        {
            medium=(low+high)/2;
            temp=medium*medium;
            if(temp==x)
            return medium;
            else if (temp<x)
            low=medium+1;
            else 
            high=medium-1;
        }
        return low*low<=x?low:low-1;        
    }
};

你可能感兴趣的:(#,Leetcode未完善,#,二分法,leetcode,c++)