本文共 1740 字,大约阅读时间需要 5 分钟。
要实现pow(x, n)函数,我们需要考虑很多特殊情况和优化点。
public class Solution { public double myPow(double x, int n) { // 处理n为0的情况 if (n == 0) return 1.0; // 处理x为-1的情况 if (Math.Abs(x) == 1.0) { if ((x > 0) && (n % 2 == 0)) return 1.0; if (x < 0 && (n % 2 != 0)) return -1.0; return 1.0; } // 处理x为1的情况 if (Math.Abs(x) == 1.0) { return x == 1.0 ? 1.0 : -1.0; } // 处理微小的浮点数误差 if ((x > 1.0 && x < 2.0) || (x < -1.0 && x > -2.0)) { // 特殊处理接近于1的值 if ((n > 0 && x == 1.0) || (n < 0 && x == -1.0)) { return 1.0; } } // 处理n为正数的情况 if (n > 0) { double result = x; int m = n; // 逐步计算,避免数值过大导致溢出的问题 do { result *= x; // 检查结果是否趋近于0 if (result < 1.0 / 1024.0) return 0.0; } while (m-- > 0); return result; } else { // 处理n为负数的情况 int m = -n; do { try { result *= result; // 检查是否结果趋近于0 if (result < 1.0 / 1024.0) return 0.0; } catch (OverflowException) { // 检查结果是否会溢出 if (result > 1.7976931348623157e+308) return 0.0; } } while (m-- > 0); // 取倒数 return 1.0 / result; } }}
转载地址:http://pegyk.baihongyu.com/