码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-06-26 00:10:03      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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

 

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

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4601161.html

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