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

【LeetCode 50】Pow(x, n)

时间:2015-08-01 15:32:20      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

Implement pow(xn).

思路:

  实现pow(xn)函数。首先,可以n次连乘x,但是这样太慢了。加速:2^10 -> 4^5 -> 16^2 * 4 ->256^1 * 4

C++:

 1 class Solution {
 2 public:
 3     double myPow(double x, int n) {
 4         
 5         if(0 == n)
 6             return 1;
 7         
 8         if(1 == n)
 9             return x;
10         
11         int index = n;
12         if(n < 0)
13             index = -n;
14         
15         double ret = index % 2 == 0 ? myPow(x * x, index >> 1) : myPow(x * x, index >> 1) * x;
16         
17         if(n < 0)
18             return 1 / ret;
19         else
20             return ret;
21     }
22 };

 

【LeetCode 50】Pow(x, n)

标签:

原文地址:http://www.cnblogs.com/tjuloading/p/4694031.html

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