首页 > 其他 > 详细

428. Pow(x, n)【medium】

时间:2018-02-04 20:33:13      阅读:152      评论:0      收藏:0      [点我收藏+]

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

会超时

 

 

 

428. Pow(x, n)【medium】

原文:https://www.cnblogs.com/abc-begin/p/8414051.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!