码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Pow(x, n)

时间:2014-09-20 01:04:26      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   div   sp   

Implement pow(x, n).

Analysis:

The most basic idea, x multiply itself n time and return.  However, this strait forward approach got time excessed. O(n).

Note that O(logn)< O(n)<O(n^2)<O(2^n).  Therefore, we should consider about recursive approach, and divide n by 2 for each recursive call.

 1 public class Solution {
 2     public double pow(double x, int n) {
 3         if (n < 0) {
 4             return 1/helper(x, -n);
 5         }
 6         else return helper(x, n);
 7     }
 8     
 9     public double helper(double x, int n) {
10         if (n == 0) return 1;
11         double half = helper(x, n/2);
12         if (n%2 == 0) {
13             return half*half;
14         }
15         else return half*half*x;
16     }
17 }

参考网上的想法,把x的n次方划分成两个x的n/2次方相乘,然后递归求解子问题,结束条件是n为0返回1。因为是对n进行二分,算法复杂度和上面方法一样,也是O(logn)。

Leetcode: Pow(x, n)

标签:style   blog   color   io   os   ar   for   div   sp   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3982752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!