50. Pow(x, n)

cemp發表於2020-10-17

C++解法:

class Solution {
public:
    double myPow(double x, int n) {
        double ans = 1.0;
        double x_contribute = x;
        long long N = abs(n);
        while(N>0){
            if(N%2==1){
                ans *= x_contribute;
            }
            x_contribute *= x_contribute;
            N /= 2;
        }
        return n>=0?ans:1./ans;
    }
};

 

相關文章