[Swift]LeetCode50. Pow(x, n) | Pow(x, n)
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9908025.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10 Output: 1024.00000
Example 2:
Input: 2.10000, 3 Output: 9.26100
Example 3:
Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10 输出: 1024.00000
示例 2:
输入: 2.10000, 3 输出: 9.26100
示例 3:
输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
- -100.0 < x < 100.0
- n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1]。
8ms
1 class Solution { 2 func myPow(_ x: Double, _ n: Int) -> Double { 3 if (n == 0) { 4 return 1 5 } 6 let temp = myPow(x, n/2) 7 if (n%2 == 0) { 8 return temp * temp 9 } 10 else { 11 if(n > 0) { 12 return x * temp * temp 13 } 14 else { 15 return (temp * temp)/x 16 } 17 } 18 } 19 }
12ms
1 class Solution { 2 func myPow(_ x: Double, _ n: Int) -> Double { 3 if n < 0 { 4 return 1 / power(x, -n); 5 } else { 6 return power(x, n); 7 } 8 } 9 private func power(_ x: Double, _ n: Int) -> Double { 10 if n == 0 { 11 return 1 12 } 13 let v = power(x, n / 2) 14 if n % 2 == 0 { 15 return v * v 16 } else { 17 return v * v * x 18 } 19 } 20 }
16ms
1 class Solution { 2 func myPow(_ x: Double, _ n: Int) -> Double { 3 if (n < 0) { 4 return 1 / myPow(x, -n) 5 } 6 if (n == 0) { 7 return 1 8 } 9 if (n == 2) { 10 return x*x 11 } 12 if (n % 2 == 0) { 13 return myPow(myPow(x, n/2), 2) 14 } 15 16 return x*myPow(myPow(x, n/2), 2) 17 } 18 }
20ms
1 class Solution { 2 func myPow(_ x: Double, _ n: Int) -> Double { 3 if n == 0 { 4 return 1 5 } 6 if n < 0 { 7 return myPow(1/x,-n) 8 } 9 return n % 2 == 0 ? myPow(x * x , n / 2) : x * myPow(x*x, n / 2) 10 } 11 }