Implement pow(x, n).
double myPow(double x, int n) {
if (x == 0) {
return 0;
}
if (n == 0) {
return 1;
}
double res = myPow(x, n / 2);
res *= res;
if (n % 2 != 0) {
if (n < 0) {
res /= x;
} else {
res *= x;
}
}
return res;
}
备忘录版本:
double myPow(double x, int n) {
if (x == 0) {
return 0;
}
if (n == 0) {
return 1;
}
int is_positive = 1;
if (n < 0) {
is_positive = 0;
n = -n;
}
double res = 1.0;
double tmp = 1.0;
while(n != 0) {
tmp *= x;
if (n % 2 == 1) {
res *= tmp;
}
n = n >> 1;
}
if (!is_positive) {
res = 1 / res;
}
return res;
}
只想说一句:廉颇老矣,尚能饭否?不能。/(ㄒoㄒ)/~~