LeetCode---50. Pow(x, n)(指数运算x的n次方)

本文介绍了一种实现pow(x, n)函数的方法,包括使用API直接计算和递归方式处理n为负数的情况。提供了两种解决方案并讨论了边界条件。

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

Implement pow(xn).

Subscribe to see which companies asked this question

//思路:主要考察越界,n为负数等问题

方法一:API

public class Solution {
    public double myPow(double x, int n) {
     //  double   Math.pow(double ,double)
        if(x==0){return 0;}
        if(n==1){return x;}
        
        double result=Math.pow(x,n);
        return result;
    }
}
方法二://考虑 n=负数边界

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

        if (n == 1) {
            return x;
        }

        boolean isNegative = false;
        if (n < 0) {
            isNegative = true;
            n *= -1;
        }

        int k = n / 2;
        int l = n - k * 2;
        double t1 = pow(x, k);
        double t2 = pow(x, l);
        if (isNegative) {
            return 1/(t1*t1*t2);
        } else {
            return t1*t1*t2;
        }
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值