# [Leetcode] Pow (x, n)

Source: Internet
Author: User

Question

Implement POW (X,N).

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 ---

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.