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

428. Pow(x, n)【medium】

时间:2018-02-04 21:00:42      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:tab   alert   diff   超时   body   class   参考   for   ram   

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】

标签:tab   alert   diff   超时   body   class   参考   for   ram   

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

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