3ms C++ solution without checking overflow


  • 0
    7

    double myPow(double x, int n)
    {

    if (n == 1)  return x;
    else if (n == 0)  return 1;
    else if (n == -1)  return 1 / x;
    double res = myPow(x, n / 2);
    if (fabs(res) < 0.00001)   //if the result is smaller than 0.00001,make it 0.
    	res = 0;
    
    if (n % 2 == 0)
    	return res * res;
    else
    	return res * myPow(x, n / 2 + n % 2);
    

    }


Log in to reply
 

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