Skip to content

Commit c2f2477

Browse files
authored
Merge pull request #178
kde_intellij
2 parents c14249c + 297870c commit c2f2477

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.concept.scala.leetcode_30days_challenge_July2020
2+
3+
/** *
4+
*
5+
* day 16
6+
*
7+
* @todo Implement pow(x, n), which calculates x raised to the power n (x pow n).
8+
* @example Example 1:
9+
*
10+
* Input: 2.00000, 10
11+
* Output: 1024.00000
12+
* Example 2:
13+
*
14+
* Input: 2.10000, 3
15+
* Output: 9.26100
16+
* Example 3:
17+
*
18+
* Input: 2.00000, -2
19+
* Output: 0.25000
20+
* Explanation: 2-2 = 1/22 = 1/4 = 0.25
21+
* @note -100.0 < x < 100.0
22+
* n is a 32-bit signed integer, within the range [−2 pow 31, 2 pow 31 − 1]
23+
*/
24+
object X_Pow_of_N {
25+
def main(args: Array[String]): Unit = {
26+
println(myPow_recursive(2.00000, -2))
27+
}
28+
29+
def myPow(x: Double, n: Int): Double = scala.math.pow(x, n)
30+
31+
32+
def myPow_recursive(x: Double, n: Int): Double = {
33+
34+
def helper(x: Double, n: Int): Double = {
35+
(x, n) match {
36+
case (_, 0) => 1
37+
case (1, _) => 1
38+
case (base, power) if power % 2 == 0 => helper(base * base, power / 2)
39+
case (base, power) => base * helper(base * base, power / 2)
40+
}
41+
}
42+
43+
if (n < 0) if (n == Int.MinValue) 1 / myPow(x, -(n + 1)) / x else 1 / myPow(x, -n) else helper(x, n)
44+
}
45+
}

0 commit comments

Comments
 (0)