Pow(x, n)
Implement pow(x, n).
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;
}
};