[Leetcode ??] 50 Pow(x, n)

Problem:

Implement pow(xn).

Analysis:

Notice n may be negative numbers.

Simply use for loop to implement is okay when n is small. When n is large enough, it may cause Time Limit Exceeded error. In this way, the time complexity is O(n).

There's a recursive implementation method can reduce the complexity to O(logn), which is faster when n is big.

Code:

 1 public class Solution {
 2     public double pow(double x, int n) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         if (n == 0) return 1;
 6         
 7         double res = 1;
 8         boolean isPos = (n>=0)?true:false;
 9         
10         n = isPos?n:-n;
11         
12         if (n%2 == 0) {
13             res = pow(x, n/2);
14             res *= res;
15         } else {
16             res = pow(x, (n-1)/2);
17             res *= x * res;
18         }
19         
20         
21         return isPos?res:1/res;
22     }
23 }
View Code

Attention:

原文地址:https://www.cnblogs.com/freeneng/p/3086607.html