-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathPow.java
More file actions
30 lines (30 loc) · 776 Bytes
/
Pow.java
File metadata and controls
30 lines (30 loc) · 776 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
package io.ziheng.recursion.divideandconquer.leetcode;
/**
* LeetCode 50. Pow(x, n)
* https://leetcode.com/problems/powx-n/
*/
public class Pow {
public double myPow(double x, int n) {
if (n < 0) {
return 1 / powDivideAndConquer(x, n);
}
return powDivideAndConquer(x, n);
}
private double powBruteForce(double x, int n) {
double r = 1;
for (; n > 0; n--) {
r = r * x;
}
return r;
}
private double powDivideAndConquer(double x, int n) {
if (n == 0) {
return 1;
}
double halfResult = powDivideAndConquer(x, n / 2);
return n % 2 == 0
? halfResult * halfResult
: halfResult * halfResult * x;
}
}
/* EOF */