zoukankan      html  css  js  c++  java
  • 剑指offer12:求解double类型的浮点数base和int类型的整数exponent的次方。 保证base和exponent不同时为0

    1. 题目描述

      给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。保证base和exponent不同时为0。

    2. 思路和方法

      分析: 由于指数是int 类型,所以要区分整数还是负数或者0。

    2.1 直接连续累乘

      会造成多次相乘运算。

    2.2 快速幂运算

      写出指数的二进制表达,例如13表达为二进制1101。 通过&1和>>1来逐位读取1101,为1时将该位代表的乘数累乘到最终结果。 举例:10^1101 = 10^0001*10^0100*10^1000。

    3.C++核心代码

    3.1 累乘

     1 class Solution {
     2 public:
     3     double Power(double base, int exponent) {
     4         int ab_e = std::abs(exponent);
     5 
     6         double res = 1.0;
     7         while(ab_e != 0) {
     8             res *= base;
     9             ab_e--;
    10         }
    11 
    12         if (exponent < 0) {
    13             res = 1.0 / res;
    14         }
    15         return res;
    16     }
    17 };
    View Code

    3.2 幂运算

     1 class Solution {
     2 public:
     3     double Power(double base, int exponent) {
     4         int ab_e = std::abs(exponent);
     5 
     6         double res = 1.0;
     7         while(ab_e) {
     8             if (ab_e & 1) {
     9                 res *= base;
    10             }
    11             base *= base;
    12             ab_e >>= 1;
    13         }
    14         if (exponent < 0){
    15             res = 1.0 / res;
    16         }
    17         return res;
    18     }
    19 };
    View Code

    参考资料

    https://blog.csdn.net/michaelhan3/article/details/88635826

  • 相关阅读:
    干草金字塔
    ⑨的完美搭积木
    门(door)
    ⑨的完美冻青蛙(frog)
    An overnight dance in discotheque
    逃跑(escape)
    BZOJ4390: [Usaco2015 dec]Max Flow
    BZOJ3732: Network
    BZOJ1121: [POI2008]激光发射器SZK
    BZOJ3713: [PA2014]Iloczyn
  • 原文地址:https://www.cnblogs.com/wxwhnu/p/11407563.html
Copyright © 2011-2022 走看看