剑指offer 面试题16 数值的整数次方

本文深入解析了快速幂算法,一种高效计算浮点数次方的方法,通过递归将复杂度降至O(logn),并提供了C++实现代码示例,包括处理正、负指数的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

保证base和exponent不同时为0

注意考虑exp为负数和零的情况,另外,求次方的时候,利用公式,
an={an/2*an/2 -------n 为偶数
a(n-1)/2*a(n-1)/2*a--------n为奇数}

降为O(logn)的复杂度
此外,可以用右移运算代替除以2,用&0x01代替%2

#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include<cmath>
#include<algorithm>
using namespace std;

class Solution {
public:
    double powerWithPos(double base,int exp) {
        if(exp==0) {
            return 1;
        } else if(exp==1) {
            return base;
        }
        double res=powerWithPos(base,exp>>1);
        res*=res;
        if(exp&0x01) {
            res*=base;
        }
        return res;
    }
    double Power(double base,int exponent) {                                                                                                                                                                                                                                                                                                                                                                                                                                    
        int neg=0;
        if(exponent<0) {
            exponent=-exponent;
            neg=1;
        }
        double res=powerWithPos(base,exponent);
        if(neg==1) {
            res=1/res;
        }
        return res;
    }
    
};

int main()
{
    Solution sol;
    int n;
    // cin>>n;
    double res=sol.Power(2,-3);
    cout<<res<<endl;
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值