标签:
Implement pow(x, n).
思路:
实现pow(x, n)函数。首先,可以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 };
标签:
原文地址:http://www.cnblogs.com/tjuloading/p/4694031.html