https://leetcode-cn.com/problems/powx-n/
中文题目:
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
英文题目:
Implement pow(x, n), which calculates x raised to the power n (x^n).
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
思路:
n is 0, return 1
n is 1,return x
n is negative, return minus -myPow(x, -n)
the calculation times only associate with n, so we begin to reduce the n times. when n is odd when minus 1 and recursion. when n is even we use x * x to calculate pow n/2.
题解:
class Solution {
public double myPow(double x, int n) {
if (n == 0.0) {
return 1.0;
}
if (n == 1) {
return x;
}
// 排除了n为-2147483648取反后越出的情况
if (n < 0) {
return 1 / (x * myPow(x, -(n + 1)));
}
// 缩短运算规模n大x小将x取平方后只要计算n/2次方即可
// 奇数n-1后再乘以x即可
return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x, n - 1);
}
}