428. Pow(x, n)【medium】

本文介绍了解决快速幂运算问题的三种方法,包括迭代法、递归法和分治法,并给出了具体的C++代码实现。

Implement pow(x, n).

 Notice

You don't need to care about the precision of your answer, it's acceptable if the expected answer and your answer 's difference is smaller than 1e-3.

Example
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1
Challenge 

O(logn) time

参考了@grandyang 的代码

 

解法一:

 1 class Solution {
 2 public:
 3     double myPow(double x, int n) {
 4         double res = 1.0;
 5         for (int i = n; i != 0; i /= 2) {
 6             if (i % 2 != 0) {
 7                 res *= x;
 8             }
 9             x *= x;
10         }
11         return n < 0 ? 1 / res : res;
12     }
13 };        

迭代

 

解法二:

 1 class Solution {
 2 public:
 3     double myPow(double x, int n) {
 4         if (n < 0) {
 5             return 1 / power(x, -n);
 6         }
 7 
 8         return power(x, n);
 9     }
10     double power(double x, int n) {
11         if (n == 0) {
12             return 1;
13         }
14 
15         double half = power(x, n / 2);
16         if (n % 2 == 0) {
17             return half * half;
18         }
19         
20         return x * half * half;
21     }
22 };

 

解法三:

 1 class Solution {
 2 public:
 3     /**
 4      * @param x the base number
 5      * @param n the power number
 6      * @return the result
 7      */
 8     double myPow(double x, int n) {
 9         if (n == 0) {
10             return 0;
11         }
12         if (n == 1) {
13             return x;
14         }
15         if (n == -1) {
16             return 1 / x;
17         }
18 
19         return myPow(x, n / 2) * myPow(x, n - n / 2);
20     }
21 };

会超时

 

 

 

转载于:https://www.cnblogs.com/abc-begin/p/8414051.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值