一、题目
二、代码
暴力解法
class Solution {
public double myPow(double x, int n) {
boolean negative = false;
//以下三种测试用例均有提交出错推断出来
if(x == 1){
return 1;
}
if(x == -1){
if(n % 2 == 1){
return -1;
}else{
return 1;
}
}
if (n == -2147483648) {
return 0;
}
if(n < 0){
n = Math.abs(n);
negative = true;
}
double result = 1.0;
for(int i = 0; i < n; i++){
result *= x;
}
return negative == true ? 1 / result : result;
}
}
递归解法
class Solution {
public double myPow(double x, int n) {
boolean negative = false;
if(n < 0){
n = - n;
negative = true;
}
return negative == false? pow(x, n) : 1.0 / pow(x, n);
}
public double pow(double x, int n){
if(n == 0){
return 1;
}
double temp = pow(x, n / 2);
if(n % 2 == 0){
return temp * temp;
}else{
return temp* temp * x;
}
}
}