Skip to content

Commit c60bfb5

Browse files
committed
[Math] Refactor solution to Pow
1 parent 41af5f4 commit c60bfb5

File tree

1 file changed

+14
-28
lines changed

1 file changed

+14
-28
lines changed

Math/Pow.swift

Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,37 +7,23 @@
77

88
class Pow {
99
func myPow(x: Double, _ n: Int) -> Double {
10-
guard n != 0 else {
11-
return 1
12-
}
13-
guard x != 0 else {
14-
return 0
15-
}
16-
17-
var res = _helper(abs(x), abs(n))
18-
10+
var x = x, n = n
11+
1912
if n < 0 {
20-
res = 1 / res
13+
x = 1.0 / x
14+
n = -n
2115
}
22-
if n % 2 != 0 && x < 0 {
23-
res = -res
16+
17+
var res = 1.0
18+
19+
while n > 0 {
20+
if n % 2 != 0 {
21+
res *= x
22+
}
23+
x *= x
24+
n /= 2
2425
}
25-
26+
2627
return res
2728
}
28-
29-
private func _helper(x: Double, _ n: Int) -> Double {
30-
guard n != 0 else {
31-
return 1
32-
}
33-
guard n != 1 else {
34-
return x
35-
}
36-
37-
if n % 2 == 0 {
38-
return _helper(x * x, n / 2)
39-
} else {
40-
return _helper(x, n - 1) * x
41-
}
42-
}
4329
}

0 commit comments

Comments
 (0)