★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(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 }