Question
Implement POW (X,N).
Answer
Use recursion:
// Recursion ("half-fold" recursion, do not use regular multiplication, low efficiency) public class solution {public double POW (Double X, int N) {If (n = 0) return 1; if (n = 1) return X; If (n =-1) return 1/X; if (N % 2 = 0) {double TMP = POW (x, N> 1); // reduce the subrecursion return TMP * TMP ;} else {return POW (x, n-1) * x ;}}}
IfWhen N is small, you can use the DP Method,Effective cache of the DP array,Performance far exceeds recursion. Of course, recursion is also advantageous. If n is large and X is not sure, the array space will be insufficient. In this case, only recursion is supported. (The DP method cannot pass,Pow (0.00001, 2147483647), it should be that the array cannot be too large)
// DP Method: Double POW (Double X, int N) {Boolean ispositive = false; If (n = 0) return 1; else if (n <0) {ispositive = true; N * =-1;} double [] result = new double [n + 1]; Result [1] = x; For (INT I = 2; I <= N; I ++) {if (I % 2 = 0) {result [I] = Result [I/2] * result [I/2];} else {result [I] = Result [I-1] * X;} If (ispositive) return 1/result [N]; elsereturn result [N];}
--- EOF ---