Solution:
pow: power.
The point is thinking of this question in recursion.
My understanding is that recursion is more expensive than simple calculation, since it relates to push and pop of memory stack.
public class Solution {
public double pow(double x, int n) {
if(n == 0) return 1;
if(n == 1) return x;
if(n < 0) {x=1/x; n=-n;}
if(n % 2 == 0) return pow(x*x, n/2);
else return x*pow(x*x, n/2);
}
}

No comments:
Post a Comment