c++ 3ms


  • 0
    G
    class Solution {
    public:
        int mySqrt(int x) 
        {
            if(x < 1)
            {
                return 0;
            }
            
            if(x == 1)
            {
                return 1;
            }
            
            int low = 1;
            int high = min(x >> 1, 46340);
            int mid = 1;
            while(low <= high)
            {
                mid = (low + high)>>1;
                int product = mid*mid;
                int greater = (mid+1)*(mid+1);
                if((product <= x) && (greater > x))
                {
                    return mid;
                }
                else if(product > x)
                {
                    high = mid - 1;
                }
                else
                {
                    low = mid + 1;
                }
            }
            
            return mid;
        }
    };
    

Log in to reply
 

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