Why did I always get "Time Limit Exceeded" at this case 0.00001, 2147483647, thanks


  • 0
    M
    class Solution {
    public:
        double myfunc(double x, int n)
        {
        	double res;
        	if(n == 1)
        	{
        		return x;
        	}
        	if(n % 2 == 1)
        	{
        		res = myfunc(x, n/2) * myfunc(x, n/2) * x;
        	}
        	else
        	{
        		res = myfunc(x, n/2) * myfunc(x, n/2);
        	}
        	return res;
        }
    
        double pow(double x, int n) {
            int count = 0;
        	double res;
        	if(n == 0)
        	{
        		return 1;
        	}
        	if(x == 0)
        	{
        		return 0;
        	}
        	res = myfunc(x, abs(n));
        	if(n < 0)
        	{
        		res = 1 / res;
        	}
        	return res;
        }
    };

  • 3
    Z

    Don't use recursive function,it costs a lot of time.
    Or you can just check whether x is smaller than 1e-15,if it is, just return 0.This is a little trick to get this 0.00001, 2147483647 case done, but the following code is more universal.
    Hope that helps,:))))

    double myfunc(double x, int n)
    {
    	double res = 1.0;
    	/*if (n == 1)
    	{
    	return x;
    	}
    	if (n % 2 == 1)
    	{
    	res = myfunc(x, n / 2) * myfunc(x, n / 2) * x;
    	}
    	else
    	{
    	res = myfunc(x, n / 2) * myfunc(x, n / 2);
    	}
    	return res;*/
    	while (n >= 1)
    	{
    		if (n % 2 == 1)
    			res *= x;
    		x *= x;
    		n /= 2;
    	}
    	return res;
    }
    
    double pow(double x, int n) {
    	if (n == 0)
    		return 1;
    
    	if (x == 0)
    		return 0;
    
    	if (n < 0)
    		return 1.0 / myfunc(x, abs(n));
    
    	return myfunc(x, abs(n));
    }

Log in to reply
 

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