題目
實(shí)現(xiàn)函數(shù)double Power(double base, int exponent)罪既,求base的exponent次方。不得使用庫(kù)函數(shù)丢间,同時(shí)不需要考慮大數(shù)問(wè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
說(shuō)明:
-100.0 < x < 100.0
n 是 32 位有符號(hào)整數(shù)诀艰,其數(shù)值范圍是 [?231, 231 ? 1] 饮六。
注意:本題與主站 50 題相同:https://leetcode-cn.com/problems/powx-n/
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán)卤橄,非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
解法
需要考慮的點(diǎn):
- x=0.0的情況喇颁;
- n為負(fù)數(shù)正數(shù)為0的情況辜膝;
- n數(shù)量級(jí)非常大漾肮,有可能超時(shí)。
思路:
最簡(jiǎn)單的辦法就是先處理特殊值:x=0單獨(dú)考慮忱辅,n為負(fù)數(shù)則結(jié)果倒數(shù)一下谭溉,用循環(huán)有多少x乘n次。
但是當(dāng)n數(shù)值非常大的時(shí)候就很容易超時(shí)了扮念,所以需要借助以下公式:
轉(zhuǎn)化成遞歸形式:
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0 : return 0 # x等于0作為特殊情況處理柜与,實(shí)際上并不等于0
if n == 0 : return 1 # 循環(huán)結(jié)束的條件
if n < 0 :
n = -n
x = 1/x
result = self.myPow(x, n>>1) # 通過(guò)右移作為除2
result *= result
if n&1 ==1: # 通過(guò)和1做與運(yùn)算 判斷奇偶數(shù)
result *= x
return result
總結(jié)
遞歸思想。