zoukankan      html  css  js  c++  java
  • 力扣算法题—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 }
  • 相关阅读:
    深入理解Java内存模型(JMM)
    Java基础知识①
    Java自旋锁的几种实现
    ConcurrentHashMap的CAS操作
    Java集合对比总结
    python模块--os模块
    python模块--random
    Datafactory 学习笔记
    Datafactory 实际使用案例
    Oracle三种排名函数使用
  • 原文地址:https://www.cnblogs.com/zzw1024/p/10628666.html
Copyright © 2011-2022 走看看