Solution leading to Time Limit Exceeded error

Hi,

PFB my solution to leetcode problem number 69. Sqrt(x). I am getting the error as time limit exceeded, but i believe it is one of the optimal solutions. Can you please help with this:

class Solution {
    public int mySqrt(int x) {
        
        if(x==0||x==1)
            return x;
        int start=1,end=x,ans=0;
        
       while(start<=end)
       {
            int mid = (start+end)/2;
        
            if(mid*mid==x)
                return mid;
         
            if(mid*mid<x)
                
            {start=mid+1;
                ans=mid;}       
            else
                end=mid-1;            
        }
        return ans;
    }
Comments (0)