Sqrt(x) in Java


  • 0
    L
    if (x == 0 || x == 1)
                return x;
    
    // We use Binary Search technique
            long start = 1, end = x;
            long result=0;
            while (start <= end)
            {
                long mid = (start + end) / 2;
                if (mid*mid == x)
                    return (int)mid;
                if (mid*mid < x)
                {
                    start = mid + 1;
                    result = mid;
                }
                    end = mid - 1;
            }
            return (int) result;
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.