简繁EN

LeetCodeNo. 019

[LeetCode with Python] 50. Pow(x, n)

Contents

Problem

Problem page: https://leetcode.com/problems/powx-n/
Topics: Math, Binary Search
Difficulty: Medium
Similar problems: (M) Sqrt(x)

Implement pow(x, n).


Analysis

Multiplying n copies of x together is hardly the kind of algorithm that belongs on LeetCode. Here I halve the exponent and use recursion to speed up the calculation.
For example, pow(x, 5) == (x * pow(x, 4)) == (x * pow(pow(x, 2), 2)).


Code

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

Article link: https://xnerv.wang/en/leetcode-pow-x-n/