首页 > 其他 > 详细

Pow(x, n)

时间:2015-04-18 12:52:22      阅读:281      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!