【LeetCode 50】Pow(x, n)

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

 

posted @ 2015-08-01 14:04  tjuloading  阅读(226)  评论(0)    收藏  举报