Find the sqrt(x) in C#


  • 0
    S
    public class Solution {
        public int MySqrt(int x) {
            int mid ;
            int left = 1;
            int right = Int32.MaxValue;
            if( x == 0)
            {
                return 0;
            }
            else if (x ==1)
            {
                return 1;
            }
            else
            {
                while(true)
                {
                    mid = left + (right-left)/2;
                    if(mid > x/mid)
                        right = mid-1;
                    else
                    {
                        if((mid+1) > x/(mid+1))
                            return mid;
                        left = mid+1;
                    }
                }
            }
        }
    }
    

Log in to reply
 

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