LeetCode 50. Pow(x, n)(分治)

本文介绍了如何解决LeetCode上的 Pow(x, n) 问题,利用分治策略实现双精度数x的32位整数n次幂的计算。详细解释了递归思路,并特别注意了负指数和整数溢出的情况。" 124536495,12821517,使用Pandas创建DataFrame详解,"['Python', '数据处理', '数据分析', 'Pandas库']
摘要由CSDN通过智能技术生成

题目来源:https://leetcode.com/problems/powx-n/

问题描述

50. Pow(x, n)

Medium

Implement pow(xn), which calculates xraised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [−231, 231 − 1]

------------------------------------------------------------

题意

求双精度数的整数(包括正整数和负整数)次幂。

------------------------------------------------------------

思路

最简单的想法是正整数n次幂转化为n次乘法,负整数次幂转化为n次乘法的倒数。分析发现有很多乘法是重复计算的,用分治法可以解决该问题。具体而言,将x^n分成x^(n/2)和x^(n/2)两个子问题(当然分成3个也可以)来解,先求出x^(n/2),然后再计算两个x^(n/2)的乘法。具体代码采用递归实现。

特别要注意的int的下限-(1<<31)的相反数比int的上限(1<<31)-1大,因此,对于x^-(1<<31)次幂的问题,不能直接转化,要转化成x^((1<<31)-1)乘x再取倒数。

------------------------------------------------------------

代码

class Solution {
    public double myPow(double x, int n) {
        if (x == 1)
        {
            return 1;
        }
        if (x == 0)
        {
            return 0;
        }
        if (n == 0)
        {
            return 1;
        }
        if (n < 0 && n > Integer.MIN_VALUE)
        {
            return 1/myPow(x, -n);
        }
        if (n == Integer.MIN_VALUE)
        {
            return 1/myPow(x, Integer.MAX_VALUE)/x;
        }
        if (n == 1)
        {
            return x;
        }
        if (n == 2)
        {
            return x * x;
        }
        double tmp = myPow(x, n/2);
        if (n % 2 == 0)
        {
            return tmp * tmp;
        }
        else
        {
            return tmp * tmp * x;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值