注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
如题,例子代码如下:
1.不调用函数:class Solution {
public:
double myPow(double x, int n) {
if(x==0)return 0;
if(n==0)return 1;
if(n==1)return x;
int m=n;
if(n<0) m=-m;
double a=x;
vector<int>way;
while(m!=1){
if(m/2==0){m=m/2;way.push_back(1);}
else {m=m-1;way.push_back(0);}
}
for(int i=0;i<way.size();i++){
if(way[i]==1)x=x*x;
else x=x*a;
}
if(n<0)return 1/x;
else return x;
}
};
2.调用函数:
double findPow(double x, int n, double a) {
if (n == 1)return x;
vector<int>way;
while (n != 1) {
if (n / 2 == 0) { n = n / 2; way.push_back(1); }
else { n = n - 1; way.push_back(0); }
}
for (int i = 0; i < way.size(); i++) {
if (way[i] == 1)x = x * x;
else x = x * a;
}
return x;
}
double myPow(double x, int n) {
if (x == 0)return 0;
double a = x;
if (n >= 1)return findPow(x, n, a);
else return 1 / findPow(x, -n, a);
} |