Not running for a partivular test case


#1

This code is showing error when A=2147483647 . How do i fix this ?

public class Solution {
public int sqrt(int A) {
int start,end,i;
long mid;
start=1;
end=A;
while(start<=end)
{
mid=(start+end)/2;
if(midmid==A)
return (int)mid;
else if(mid
mid>A)
end=(int)mid-1;
else if(midmid<A)
{
if((mid+1)
(mid+1)>A)
return (int)mid;
else
start=(int)mid+1;
}
}
return 0;
}
}


#2

Hey, you are experiencing integer overflow.
2147483647 is the maximum value an int can hold in Java (as per Google).
when A=2147483647, in the calculation of mid, when you do
mid=(start+end)/2,
start+end=1+2147483647
and thus this term overflows
to avoid this, either you can do start+(end-start)/2 or just change the types of start and end from int to long.
I have used the later fix in the code below.

public class Solution {
    public int sqrt(int A) {
    long start,end,i;
    long mid;
    start=1;
    end=A;
    while(start<=end)
    {
        mid=(start+end)/2;
        if(mid*mid==A)
            return (int)mid;
        else if(mid*mid>A)
            end=(int)mid-1;
        else if(mid*mid<A)
        {
            if((mid+1)*(mid+1)>A)
            return (int)mid;
            else
            start=(int)mid+1;
        }
    }
    return 0;
    }
}