3ms C++ solution beats 100%


  • -1
    B
    class Solution {
    public:
        int mySqrt(int x) {
            int l , h = 1;
    	if (x <= 10)
    	{
    		if (x == 0 || x == 1)
    			return x;
    		l = 0;
    		h = x;
    	}
    	else
    	{
    	        int n = x,b;
    		for (int i = 0; n > 0; i++)
    		{
    			n = n / 10;
    			b = i;
    		}
    		for (int i = 0; i < b/2; i++)
    			h = h * 10;
    	        h = h * 10;
    		l = h / 100;
    	}
    	while (x  / ((l + h)/2)!= (l + h) / 2)
    	{
    		if (x  / ((l + h)/2) < (l + h) / 2)
    			h =  (h + l) / 2;
    		else
    		{
    			l = (h + l) / 2;
    		}
    		if (h - l == 1)
    		{
    			if (x/h == h)
    				return h;
    			else
    			{
    				return l;
    			}
    		}
    	}
    	return (l + h) / 2;
        }
    };

Log in to reply
 

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