Steve Zhang Steve Zhang - 4 months ago 12
Java Question

What is wrong of my solution for the Leetcode puzzle Sqrt(x)?

I am working on the LeetCode question No.69 named sqrt(x)(https://leetcode.com/problems/sqrtx/). It asked me to return the square root of the integer also in another integer. Below is my solution.

public class Solution {
public int mySqrt(int x) {
int i = 0;
if(x==0)
{
return 0;
}
for(i = 1;i<x/2;i++)
{
if(((i*i)<=x)&&((i+1)*(i+1)>x))
{
break;
}
}

return i;
}
}


After I submit the code, all the test cases where x >= 2147395600 are all failed. When x = 2147395600, it is returning a 289398 instead of 46340, which is the right answer. What is the problem with my code?

Answer

You can try my code:

public int mySqrt(int x) {
        long i = 0;
        long j = x;
        int mid = 0;
        if (x == 0) {
            return 0;
        }
        if (x == 1) {
            return 1;
        }
        while (i <= j) {
            mid = (int)(i + j)/2;
            if (x/mid == mid) {
                return (int)mid;
            } else if (x/mid > mid) {
                i = mid + 1;
            } else if (x/mid < mid) {
                j = mid - 1;
            }
        }
        return (int)j;
        }