問題:java
Implement pow(x, n).spa
解決:遞歸
① 調用java API。io
class Solution { //28ms
public double myPow(double x, int n) {
return Math.pow(x,n);
}
}class
② pow(x,n)就是求x的n次方。x的n次方能夠看作:x^n = x^(n/2)*x^(n/2)*x^(n%2)。因此利用遞歸求解,當n==1的時候,x^n=x。效率
固然n是能夠小於0的,2^(-3) = 1/(2^3)。按照上面那個規律就能夠解決了。方法
class Solution { // 22ms
public double myPow(double x, int n) {
if(n < 0) return 1 / x * myPow(1 / x, - (n + 1));
if(n == 0) return 1;
if(n == 2) return x * x;
if(n % 2 == 0) return myPow( myPow(x, n/2), 2);
else return x * myPow(myPow(x, n/2), 2);
}
}co
③ 單獨寫一個方法效率更高return
class Solution {//19ms public double myPow(double x, int n) { if (n < 0) { return 1 / powerHelper(x, -n); } else { return powerHelper(x, n); } } private double powerHelper(double x, int n) { if (n == 0) return 1; if (n == 1) return x; double temp = powerHelper(x, n/2); if (n % 2 == 0) { return temp * temp; } else { return temp * temp * x; } } }