Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1702 from a93a/50
Browse files Browse the repository at this point in the history
Create 0050-powx-n.kt
  • Loading branch information
Ahmad-A0 authored Dec 29, 2022
2 parents c1c82b2 + 408256b commit 0e607bf
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions kotlin/0050-powx-n.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class Solution {
fun myPow(x: Double, n: Int): Double {
val sum = myPowHelper(x, n)
return if(n < 0) 1/sum else sum // if power to the negative
}
private fun myPowHelper(x: Double, n: Int): Double {
if(x == 0.0)
return 0.0
when(n){
0 -> return 1.0
1 -> return x
else -> {
var res = myPowHelper(x, n/2)
res *= res
return if(n%2==0) res else x * res //if odd number, we multiply the "lost" number from integer division
}
}
}
}

0 comments on commit 0e607bf

Please sign in to comment.