FWNX - power(double x,int n) - C++version

本文介绍了一种使用递归实现快速幂运算的方法,并考虑了不同情况下的整数指数运算,包括正数、负数及偶数、奇数的情况。通过递归计算一半的幂次再进行平方或乘以基数的方式加速计算过程。

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

class Solution {
public:
    double pow(double x, int n) {
        if (n == 0) return 1;	 //	if n == 0; return 1;


	double half = pow(x, n/2);


	if (n % 2 == 0) return half * half;	//if n is even return power(x,n/2) *  power(x,n/2)
	else
	if(n%2 ==1 || n%2 == -1)
	{
	    if(n > 0) return half*half*x;
	    if(n<0)
	    {
	        return half*half*(1/x);
	    }
	}
	
    }
};

1 =  when you met the int n we must consider this in the four case :

       1.1 odd negative

       1.2 odd positive

       1.3 even positive 

1.4 even positive

2 = wonderful recursive

      calculate the half at first and then use this half to calculate the whole

but we must give the base value before the calculating of half or dead loop

3 = the negative odd % 2 = -1

the positive odd % 2 = 1

the negative and positive even %2 = 0

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值