Pow(x, n)

06/27/2016 Binary Search Math

Question

Implement pow(x, n).


Solution

Result: Accepted Time: 0 ms

Here should be some explanations.

double myPow(double x, int n) {
    double ans = 1;
    if(n < 0)
    {
        x = 1.0/x;
        ans = x;
        n = -(n+1);
    }
    while(n)
    {
        if(n&1)
            ans *= x;
        n >>=1;
        x *=x;
    }
    return ans;
}

Complexity Analytics

  • Time Complexity:
  • Space Complexity: