【思路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 };

 

相关文章:

  • 2021-12-03
  • 2021-11-20
  • 2022-01-13
  • 2021-12-01
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-15
  • 2022-12-23
  • 2021-12-17
  • 2021-06-12
  • 2021-09-16
  • 2022-02-19
  • 2021-09-10
相关资源
相似解决方案