LeetCode Pow(x,n)

来源:互联网 发布:编程算法基础pdf 编辑:程序博客网 时间:2024/05/25 23:17

Pow(x, n)

Implement pow(xn).

Tips:

Notice negetive pows.

Solution:

class Solution {public:    double pow(double x, int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<double> pows;        double result=1;        if(n<0){            n=-n;            x=1/x;        }                    pows.push_back(x);        long long i=1;        while(i*2<=n){            pows.push_back(pows.back()*pows.back());            i*=2;        }        int index=pows.size()-1;        while(n>0){            if(n>=i){                result*=pows[index];                n-=i;            }            i/=2;            --index;        }        return result;    }};

原创粉丝点击