★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-viqpikzs-me.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Implement pow(x, n), which calculates x raised to the power n (xn).git
Example 1:github
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:spa
实现 pow(x, n) ,即计算 x 的 n 次幂函数。code
示例 1:htm
输入: 2.00000, 10 输出: 1024.00000
示例 2:blog
输入: 2.10000, 3 输出: 9.26100
示例 3:get
输入: 2.00000, -2 输出: 0.25000 解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
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 }