We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 41af5f4 commit c60bfb5Copy full SHA for c60bfb5
Math/Pow.swift
@@ -7,37 +7,23 @@
7
8
class Pow {
9
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
+ var x = x, n = n
+
19
if n < 0 {
20
- res = 1 / res
+ x = 1.0 / x
+ n = -n
21
}
22
- if n % 2 != 0 && x < 0 {
23
- res = -res
+ var res = 1.0
+ while n > 0 {
+ if n % 2 != 0 {
+ res *= x
+ }
+ x *= x
24
+ n /= 2
25
26
27
return res
28
29
- private func _helper(x: Double, _ n: Int) -> Double {
30
31
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
43
0 commit comments