题目链接:click~
/*题意:求x的n次方*/
/**
*思路: 二分:
* n为偶数,x^n= (x^(n/2))*(x^(n/2))
* n为奇数,只需要再乘以x
*/
class Solution {
public:
double pow(double x, int n) {
if(n == 0) return 1;
if(n == 1) return x;
if(n < 0) x = 1/x; //n为负数时
int m = abs(n); //取绝对值
double res = pow(x, m>>1);
res *= res;
if(m%2 == 1) res *= x;
return res;
}
};