标签:
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;
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 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4437070.html