LeetCode/剑指offer 实现pow(x,y),不得使用工具类,不考虑大数问题
知识点:
- 快速幂乘法
- 考虑y为负数的情况
- 考虑y为Integer.MIN_VALUE时候,变成正数会超出范围,因此需要用long存储
- 不能直接Integer.MIN_VALUE*-1,否则会溢出还是等于Integer.MIN_VALUE,需要先用long存储,再乘-1
public static double myPow(double x, int n) {
double ret = 1.0;
int flag = n < 0 ? -1 : 1;
long cur = n;
cur *= flag;
double contribute = x;
while (cur > 0) {
if (cur % 2 == 1) ret *= contribute;
contribute *= contribute;
cur = cur/2;
}
return flag == -1 ? 1 / ret : ret;
}