码迷,mamicode.com
首页 > 其他好文 > 详细

Pow(x, n)

时间:2015-04-18 12:55:36      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

Implement pow(xn).

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 };

 

Pow(x, n)

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4437070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!