力扣算法题—050计算pow(x, n)

 1 #include "000库函数.h"
 2 
 3 
 4 
 5 //使用折半算法  牛逼算法
 6 class Solution {
 7 public:
 8     double myPow(double x, int n) {
 9         if (n == 0)return 1;
10         double res = 1.0;
11         for (int i = n; i != 0; i /= 2) {
12             if (i % 2 != 0)
13                 res *= x;
14             x *= x;
15         }
16         return n > 0 ? res : 1 / res;
17     }
18 
19 };
20 
21 
22 //同样使用二分法,但是使用递归思想
23 class Solution {
24 public:
25     double myPow(double x, int n) {
26         if (n == 0)return 1;
27         double res = myPow(x, n / 2);
28         if (n % 2 == 0)return x * x;//是偶数,则对半乘了之后再两个大数相乘,x^n==(x^n/2)^2
29         if (n > 0) return res * res * x;
30         return res * res / x;
31     }
32 };
33 
34 void T050() {
35     Solution s;
36     double x;
37     int n;
38     x = 0.0001;
39     n = 2147483647;
40     cout << s.myPow(x, n) << endl;
41     x = 2.1;
42     n = 3;
43     cout << s.myPow(x, n) << endl;
44     x = 2;
45     n = -2;
46     cout << s.myPow(x, n) << endl;
47     x = 0.9;
48     n = 2147483647;
49     cout << s.myPow(x, n) << endl;
50 
51 
52 }

 

posted @ 2019-03-30 19:45  自由之翼Az  阅读(348)  评论(0编辑  收藏  举报