1 class Solution { 2 public: 3 double Power(double base, int exponent) { 4 double res=1.0; 5 if(base==0) return 0; 6 if(exponent==0) return 1; 7 if(exponent<0){ 8 base = 1.0/base; 9 exponent = -exponent; 10 } 11 for(int i=0;i<exponent;i++){ 12 res = res*base; 13 } 14 return res; 15 } 16 };
1 递归 2 class Solution { 3 public: 4 double Power(double base, int exponent) { 5 6 if(exponent == 0) return 1; 7 if(base == 0) return 0; 8 if(exponent == 1) 9 return base; 10 else if(exponent == -1) 11 return 1/base; 12 return Power(base,exponent/2) * Power(base,exponent/2) * Power(base,exponent%2); 13 } 14 };
1 class Solution { 2 public: 3 double Power(double base, int exponent) { 4 if(exponent>0) 5 { 6 if(exponent==1) 7 return base; 8 if(exponent%2==0) 9 return Power(base,exponent/2)*Power(base,exponent/2); 10 else 11 return Power(base,exponent/2)*Power(base,exponent/2+1); 12 } 13 else if (exponent==0) 14 { 15 return 1; 16 } 17 else 18 { 19 return 1/Power(base,0-exponent); 20 } 21 } 22 };
快速幂
1 class Solution { 2 public: 3 double Power(double base, int exponent) { 4 long long p=abs((long long) exponent); 5 double r = 1; 6 if(base==0) return 0; 7 while(p){ 8 if(p&1) r *= base; 9 base *= base; 10 p>>=1; 11 } 12 return exponent<0? 1/r: r; 13 } 14 };