topic:
50、Pow(x, n)
Realize pow(x, n), that is, calculate the n-th power function of x (ie, xn).
Example 1:
Example 2:
Example 3:
Prompt:
Problem solution ideas:
Dichotomy, through the calculation of halves, each time n is halved, reducing the time complexity.
Two ways of writing:
one, ordinary writing.
2. Bitwise arithmetic writing.
Note: In fact, they all have the same meaning and achieve the same effect. The speed is also similar.
For example, n>>=1 is equivalent to n/=2; n%2 == 1 is equivalent to n&1 == 1 (judge whether it is an odd number)
Problem solution python code:
1. Common writing
class Solution:
def myPow(self, x: float, n: int) -> float:
res = 1
if n < 0: x,n = 1/x,-n
while n: # 通过折半计算,每次把 n 减半,降低时间复杂度
if n%2 == 0:
x *= x
n /= 2
else:
res *=x
n -= 1
return res
Two, bit operation writing
class Solution:
def myPow(self, x: float, n: int) -> float:
res = 1
if n < 0: x, n = 1 / x, -n
while n:
if n & 1: res *= x
x *= x
n >>= 1
return res
Author: a-qing-ge
Links: https://leetcode-cn.com/problems/powx-n/solution/er-fen-fa-pu-tong-xie-fa-yi-ji-wei-yun-s -cw8x/
Source: LeetCode https://leetcode-cn.com/problems/powx-n/