LeetCode—50. Pow(x, n)

Type:medium

Implement pow(x, n), which calculates x raised to the power n (xn).


给定x,n。求出x的n次方。

x^10 = x^5 * x^5 = (x^2 * x^2 * x) * (x^2 * x^2 * x)

递归法即可。


class Solution {

public:

    double myPow(double x, int n){

        if(n == 0) return 1.0;

        long temp = n;

        if(temp<0) return 1/(rr(x, -temp));

        else return (rr(x, temp));

    }


    double rr(double x, long n) {

        if(n == 0) return 1.0;

        else if(n%2 == 0) {

            double temp = myPow(x, n/2);

            return temp * temp;

        }else {

            double temp = myPow(x, n/2);

            return x * temp * temp;

        }     

    }

};

你可能感兴趣的:(LeetCode—50. Pow(x, n))