Implement pow(x, n).
Analyse: To avoid exceeding time, first consider the basic situation, see line5~11; then set some precision s.t. when the difference of result and 0 is less than that precision, return 0;
好的解法:7ms
1 class Solution{ 2 public: 3 double pow(double x, int n){ 4 if(n == 0) return 1; 5 if(x == 1) return 1; 6 if(x == -1) return (n % 2 == 0 ? 1 : -1); 7 8 if(n < 0) 9 return 1.0 / pow(x, -n); 10 else 11 return power(x, n); 12 } 13 private: 14 double power(double x, int n){ 15 if(n == 0) return 1; 16 double temp = power(x, n/2); 17 if(n % 2 == 0) return temp * temp; 18 else return temp * temp * x; 19 } 20 };
自己写的: 32ms
1 class Solution { 2 public: 3 double pow(double x, int n) { 4 double result = 1.00; 5 if(n == 0) return result; 6 if(x == 0) return 0; 7 if(x == 1) return 1; 8 if(x == -1){ 9 if(n % 2 == 0) return 1; 10 else return -1; 11 } 12 13 if(n < 0){ 14 n = -n; 15 x = 1 / x; 16 } 17 18 for(int i = 0; i < n; i++){ 19 result *= x; 20 if(abs(result - 0) < 0.0000000001) return 0; 21 } 22 return result; 23 } 24 };