Skip to content

Commit

Permalink
[Math] Refactor solution to Pow
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Jan 20, 2020
1 parent 41af5f4 commit c60bfb5
Showing 1 changed file with 14 additions and 28 deletions.
42 changes: 14 additions & 28 deletions Math/Pow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,23 @@

class Pow {
func myPow(x: Double, _ n: Int) -> Double {
guard n != 0 else {
return 1
}
guard x != 0 else {
return 0
}

var res = _helper(abs(x), abs(n))

var x = x, n = n

if n < 0 {
res = 1 / res
x = 1.0 / x
n = -n
}
if n % 2 != 0 && x < 0 {
res = -res

var res = 1.0

while n > 0 {
if n % 2 != 0 {
res *= x
}
x *= x
n /= 2
}

return res
}

private func _helper(x: Double, _ n: Int) -> Double {
guard n != 0 else {
return 1
}
guard n != 1 else {
return x
}

if n % 2 == 0 {
return _helper(x * x, n / 2)
} else {
return _helper(x, n - 1) * x
}
}
}

0 comments on commit c60bfb5

Please sign in to comment.