forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPow.java
More file actions
27 lines (25 loc) · 630 Bytes
/
Pow.java
File metadata and controls
27 lines (25 loc) · 630 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Pow {
/**
* 这道题要注意的有几点:
* 1. n为0的情况
* 2. n为负数的情况,要给n变为正,同时x取倒
* 3. n由负变正可能会溢出,所以要改成long
*/
public double myPow(double x, int n) {
return helper(x, n);
}
private double helper(double x, long n) {
if (n == 0) {
return 1;
}
if (n < 0) {
return helper(1 / x, -n);
}
double y = helper(x, n / 2);
if (n % 2 == 0) {
return y * y;
} else {
return y * y * x;
}
}
}