Skip to content

Commit 7760432

Browse files
committed
Updated pow
1 parent ca13986 commit 7760432

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

Medium/Pow.java

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,19 @@ public static void main(String[] args) {
1010
}
1111

1212
/**
13-
* Divide n by 2
14-
*
13+
* Binary Search, divide n by 2
1514
* Questions:
1615
* 1. can x be zero?
1716
* 2. can n be negative?
17+
*
1818
* When n is odd, multiply result by f
1919
* f multiply by itself each time
20-
* Repeat until n <= 0
20+
* Repeat until n == 0
21+
* x^10 = x^2 * x^8
22+
* x^9 = x * x^8
23+
* x^8 = x^8
24+
* x^7 = x * x^2 * x^4
25+
* x^6 = x^2 * x^4
2126
*/
2227
public double pow(double x, int n) {
2328
if (n == 0) return 1;
@@ -26,9 +31,9 @@ public double pow(double x, int n) {
2631
x = 1 / x; // x can be zero?
2732
}
2833
double res = 1; // mind overflow
29-
for (double f = x; n > 0; n = n >> 1) { // n/=2
34+
for (double f = x; n > 0; n = n >> 1) { // n >>= 1, n/=2
3035
if (n % 2 == 1) res *= f;
31-
f = f * f;
36+
f = f * f; // f *= f
3237
}
3338
return res;
3439
}

0 commit comments

Comments
 (0)