Thursday, January 8, 2015

LeetCode 69: Sqrt(x)

Implement int sqrt(int x).
Compute and return the square root of x.
public class Solution {
    public int sqrt(int x) {
        // sqrt(x) should be less than x/2 + 1.
        // Adopt binary search
        // Note: we should use long type in case of overflow.
        if (x == 0)
            return 0;
            
        long lo = 0;
        long hi = x/2+1;
        
        while (lo <= hi)
        {
            long mid = lo + (hi-lo)/2;
            
            long square = mid*mid;
            
            if (square > x)
                hi = mid - 1;
            else if (square < x)
                lo = mid + 1;
            else
                return (int)mid;
        }
        
        return (int)lo-1;
    }
}

No comments:

Post a Comment