Implement pow(x, n).
» Solve this problem
这题的坑在于n可能为负数。
一定要注意!!
class Solution {
public:
double pow_positive(double x, int n) {
if (n == 0) {
return 1;
}
else if (n == 1) {
return x;
}
else {
double t = pow(x, n / 2);
return t * t * ((n & 1) == 0 ? 1 : x);
}
}
double pow(double x, int n) {
return n < 0 ? 1 / pow_positive(x, -n) : pow_positive(x, n);
}
};
public class Solution {
public double pow(double x, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
switch (n) {
case 0:
return 1;
case 1:
return x;
case -1:
return 1 / x;
}
double temp = pow(x, n / 2);
return temp * temp * ((n & 1) == 0 ? 1 : (n > 0 ? x : 1 / x));
}
}