[LeetCode][JavaScript]Pow(x, n)

Pow(x, n)

Implement pow(xn).

https://leetcode.com/problems/powx-n/

 

 


 

 

注意x和n都可能是负数。

递归,二分折半,比如求3的4次方,可以拆成3的2次方相乘;3的5次就是3^2相乘再乘2。

 1 /**
 2  * @param {number} x
 3  * @param {number} n
 4  * @return {number}
 5  */
 6 var myPow = function(x, n) {
 7     if(n >= 0){
 8         return pow(Math.abs(n));
 9     }else{
10         return 1 / pow(Math.abs(n));
11     }
12     
13     function pow(n){
14         var temp = 0;
15         if(n === 0){
16             return 1;
17         }else if(n === 1){
18             return x;
19         }else if(n % 2 === 1){
20             temp = pow((n - 1) / 2);
21             return temp * temp * x;
22         }else if(n % 2 === 0){
23             temp = pow(n / 2);
24             return temp * temp;
25         }
26     }
27 };

 

posted @ 2015-06-25 22:52  `Liok  阅读(773)  评论(0编辑  收藏  举报