Implement pow(x, n).
思考:一开始想的太复杂了,跟这一题联系起来了(链接)。后来看到返回值是double型,所以此题就没有那么复杂了。毕竟面试题不会要求写一大堆代码的,最重要的还是考察算法思想:快速幂取模,当然这里不用取模。
class Solution {
public:
double pow(double x, int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(n==0) return 1;
double ans=pow(x,n/2);
if(n%2==0)
return ans*ans;
else if(n>0)
return x*ans*ans;
else
return ans*ans/x;
}
};