An iterative solution


  • 4
    M

    Think exponent as binary number.

    double pow(double x, int n) {
        if(n==0)
            return 1;
        if(n < 0)
            return 1 / power(x, -n);
        return power(x,n);
    }
    
    double power(double x, int n) {
        double result = 1;
        while(n > 0) {
            if(n & 1)
                result *= x;
            x *= x;
            n >>= 1;
        }
        return result;
    }

  • 0
    H

    i like the idea of bit operation!


Log in to reply
 

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