【思路1】递归
1 class Solution { 2 public: 3 double Power(double base, int exponent) { 4 if(exponent < 0){ 5 base = 1/base; 6 exponent = -exponent; 7 } 8 if(exponent == 0){ 9 return 1;10 }else{11 return base * Power(base, exponent - 1);12 }13 }14 };
【思路2】快速幂
1 class Solution { 2 public: 3 double Power(double base, int exponent) { 4 long long p = abs((long long)exponent); 5 double ans = 1.0; 6 while(p != 0) { 7 if(p & 1) { 8 ans *= base; 9 }10 base *= base;11 p >>= 1;12 }13 return exponent > 0 ? ans : 1/ans;14 }15 };