Pow(x, n)

Implement pow(xn).

思路

二分,然后注意特殊情况的判断。

最开始提交好几次都不成功。超时是因为使用递归的时候算了两次,应该用一个变量把值存起来然后直接使用的。WA是因为忘记了负数模2可能得到-1的情况。

 1     double pow(double x, int n) {
 2         // Note: The Solution object is instantiated only once and is reused by each test case.
 3         if(x == 0 || x == 1)
 4             return x;
 5         if(x == -1)
 6             return n%2==1?(-1):1;
 7         if(n == 0)
 8             return 1;
 9         if(n == 1)
10             return x;
11         if(n == -1)
12             return 1/x;
13         double tmp = pow(x, n/2);
14         return tmp*tmp*pow(x, n%2);
15     }
原文地址:https://www.cnblogs.com/waruzhi/p/3372925.html