题目来源:https://leetcode.com/problems/powx-n/
问题描述
50. Pow(x, n)
Medium
Implement pow(x, n), 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;
}
}
}