简繁EN

LeetCodeNo. 019

【LeetCode with Python】 50. Pow(x, n)

目錄

題目

原題頁面:https://leetcode.com/problems/powx-n/
題目型別:Math, Binary Search
難度評價:Medium
類似題目:(M) Sqrt(x)

Implement pow(x, n).


分析

用n個x相乘顯然不是應該出現在leetcode上的演算法。這裡是利用二分的演算法,通過遞迴來加速計算。
例如,pow(x, 5) == (x * pow(x, 4)) == (x * pow(pow(x, 2), 2))。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
# @param x, a float
# @param n, a integer
# @return a float
def pow(self, x, n):
if 0 == n:
return 1
elif n < 0:
return 1.0 / self.pow(x, -n)
else:
half = self.pow(x, n >> 1)
if 0 == n % 2:
return half * half
else:
return x * half * half

本文地址:https://xnerv.wang/zh-tw/leetcode-pow-x-n/