-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain16.java
More file actions
50 lines (47 loc) · 926 Bytes
/
Main16.java
File metadata and controls
50 lines (47 loc) · 926 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package JZOffer2;
/**
* 递归写法
*/
public class Main16 {
public double myPow(double x, int n) {
return myPow(x, (long) n);
}
private double myPow(double x, long b) {
if (b == 0)
return 1.0;
if (b < 0) {
x = 1 / x;
b = -b;
}
if (b % 2 == 1) {
return myPow(x, b - 1) * x;
} else {
double temp = myPow(x, b / 2);
return temp * temp;
}
}
}
/**
* 非递归快速幂
*/
class Main16_1 {
public double myPow(double x, int n) {
if(x == 0) {
return 0;
}
long b = n;
double res = 1.0;
if(b < 0) {
x = 1 / x;
b = -b;
}
while (b > 0) {
if((b & 1) == 1) {
res *= x;
}
x *= x;
b >>= 1;
}
return res;
}
}