diff --git a/notes/16. 数值的整数次方.md b/notes/16. 数值的整数次方.md index b20367e2..b617a4f8 100644 --- a/notes/16. 数值的整数次方.md +++ b/notes/16. 数值的整数次方.md @@ -2,7 +2,7 @@ ## 题目链接 -[牛客网](https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) +[Leetcode](https://leetcode.cn/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/) ## 题目描述 @@ -24,19 +24,17 @@ 因为 (x\*x)n/2 可以通过递归求解,并且每次递归 n 都减小一半,因此整个算法的时间复杂度为 O(logN)。 ```java -public double Power(double x, int n) { - boolean isNegative = false; - if (n < 0) { - n = -n; - isNegative = true; +public double myPow(double x, int n) { + long b = n; + if (b < 0) { + x = 1 / x; + b = -b; } - double res = pow(x, n); - return isNegative ? 1 / res : res; + return pow(x, b); } -private double pow(double x, int n) { +private double pow(double x, long n) { if (n == 0) return 1; - if (n == 1) return x; double res = pow(x, n / 2); res = res * res; if (n % 2 != 0) res *= x;