mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 18:23:52 +00:00
Update 16. 数值的整数次方.md
题目链接改为力扣中的对应题目,方法签名按该题调整,指数取相反数前先转为 long。
This commit is contained in:
+8
-10
@@ -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)<sup>n/2</sup> 可以通过递归求解,并且每次递归 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;
|
||||
|
||||
Reference in New Issue
Block a user