Saturday, May 4, 2013

Leetcode: Sqrt in C++


Implement int sqrt(int x).
Compute and return the square root of x.
Solution:
int sqrt(int x) {
        int start  = 0;
        int end = x;
        double cur = x;
        while(start<=end)
        {
            double mid = start + (end-start)/2;
            double result = mid*mid;
            if(result == cur)
            return mid;
            else if(result>cur)
            end = mid-1;
            else
            start = mid+1;
        }
        return end;
    }

No comments:

Post a Comment