- 算法
- 1.递归
- 2.如果n小于0,x取倒数,使n大于0,转换为正数幂
- 3.如果n大于等于0,分为奇数和偶数递归计算
- ps:防止溢出使用long整型
public double myPow(double x, int n) { if (n < 0) { long l = - (long) n; return 1.0 / myPowOfPositive(x, l); } else { return myPowOfPositive(x, n); } } private double myPowOfPositive(double x, long n) { if (n == 0) { return 1.0; } if ((n & 1) == 0) { return myPowOfPositive(x * x, n >> 1); } else { return myPowOfPositive(x * x, (n - 1) >> 1) * x; } }