数值的整数次方

  1. 题目描述
  2. 思路分析

题目描述

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

思路分析

  • 快速幂
  • 幂运算依次增大
class Solution {
public:
    double Power(double base, int exponent) {
        double res = 0;
        int exp = 1,flag = 1;
        if (exponent < 0){ // 负整数幂
            exponent = -exponent;
            flag = 0;
        }
        if (exponent == 0){// 幂次为0,返回1
            res = 1;
        }else if (exponent == 1){// 幂次为1,返回底数本身
            res = base;
        }else{ 
            // 快速幂
            int nbase = base;
            while(exponent > exp*2){ // 指数小于当前幂次的两杯
                res = nbase*nbase;  // 求幂
                nbase = res;        // 更新结果
                exponent -= exp*2;  // 减少目标幂次
                exp++;              // 增大幂次
            }
            // 处理剩余的幂运算
            for (int i = 0;i < exponent;++i){
                res *= base;
            }
        }
        return flag == 1?res:1/res;
    }
};

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:数值的整数次方

Count:185

Author:攀登

Created At:2019-12-26, 23:12:31

Updated At:2024-06-15, 15:53:35

Url:http://jiafeimao-gjf.github.io/2019/12/26/sword-%E6%95%B0%E5%80%BC%E7%9A%84%E6%95%B4%E6%95%B0%E6%AC%A1%E6%96%B9/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation