50. Pow(x, n)
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/powx-n
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Scanner;
class Solution {
public static double myPow(double x, int n) {
double ret = 1;
if (n < 0) {
x = 1 / x;
if (n == Integer.MIN_VALUE) {
ret *= x;
n = Integer.MAX_VALUE;
} else {
n = -n;
}
}
double base = x;
while (n > 0) {
if ((n & 1) == 1) {
ret *= base;
}
base *= base;
n >>= 1;
}
return ret;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(myPow(in.nextDouble(), in.nextInt()));
}
}
}