Pow(x, n)

本文介绍了一种快速幂运算的方法,并提供了两种不同的实现方案。一种是在7毫秒内完成计算的高效算法,另一种则较为简单但运行时间较长。通过递归方式减少乘法次数,有效提升了计算效率。

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;

好的解法: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 };

 

转载于:https://www.cnblogs.com/amazingzoe/p/4437070.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值