原题链接在这里:https://leetcode.com/problems/powx-n/
这道题和Sqrt(x)以及Divide Two Integers都是原有公式的题。这类题目一般用二分法(Sqrt(x))和以2为基地accumulation表示法(Divide Two Integers)都是为了节省时间到O(logn).
这里采用了二分法,建立一个helper返回n为正数时的power, 主函数里分开调用即可。
helper中采用递归,原理就是x^n = x^(n/2) * x^(n/2) * (n == 奇数)*x, 终止条件是n==0时返回一.
AC Java:
public class Solution {
public double myPow(double x, int n) {
if(n<0){
return 1/helper(x,-n);
}else{
return helper(x,n);
}
}
private double helper(double x, int n){
if(n == 0){
return 1.0;
}
double half = helper(x,n/2);
if(n%2 == 0){
return half * half;
}else{
return half * half * x;
}
}
}