Letcode 题:pow(x,n)

最初的想法,将输入乘以n-1次,时间复杂度为O(n),结果运行结果超时

 1 public class Solution {
 2     public double pow(double x, int n) {
 3         double result = x;
 4         double tmp = 1/x;
 5         if(n == 0)
 6             return 1;
 7         
 8         if(n > 0){
 9             for(int i = 1; i < n; i++)
10                 result = result * x;
11         } else{
12             for(int j = n; j < -1; j++)
13                 result = result * tmp;
14         }
15             
16         return result;
17         
18     }
19 }

 

2.用二分:
xn = xn/2 * xn/2 * xn%2
时间复杂度:O(logN)
这样,使用递归函数,大数据超时

 1     public double pow(double x, int n) {
 2         double result = x;
 3         if (x == 0){
 4             if(n == 0)
 5                 return 1;
 6             else
 7                 return 0;
 8         }
 9 
10         if (n == 0)
11             return 1;
12         if (n == 1)
13             return x;
14             
15         if (n == -1)
16             return 1/x;
17         
18         if(n >= 2)
19             return pow(x, n / 2) * pow(x, n / 2) * pow(x, n % 2);
20         else{
21             int absn = Math.abs(n);
22             return 1 / (pow(x, absn / 2) * pow(x, absn / 2) * pow(x, absn % 2));
23         }
24             
25     }

 

 

你可能感兴趣的:(code)