LeetCode 50. Pow(x, n)
Woodyiiiiiii opened this issue · comments
Implement pow(x, n)
, which calculates x raised to the power n (i.e. xn).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Constraints:
-100.0 < x < 100.0
-231 <= n <= 231-1
-104 <= xn <= 104
题目要求我们重写pow方法。
对幂次方n做一个二分,递归调用。
class Solution {
public double myPow(double x, int n) {
double temp;
if(n == 0) return 1;
temp = myPow(x, n/2);
if (n % 2 == 0)
return temp*temp;
else{
if(n > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
}
或者使用快速幂。注意,因为-2147483648无法用Math.abs()化为正数,所以要特殊处理。
class Solution {
public double myPow(double x, int n) {
if (n == 0) return 1.0;
if (n == Integer.MIN_VALUE) {
if (x == 1.0) return 1.0;
if (x == -1.0) return 1.0;
return 0.0;
}
int absN = Math.abs(n);
double base = x, ans = 1.0;
while (absN > 0) {
if (absN % 2 == 1) {
ans *= base;
}
base *= base;
absN >>= 1;
}
return n < 0 ? 1 / ans : ans;
}
}
类似题目:
参考资料: