Likou brushing notes: 50.Pow(x, n) (two ways of writing, dichotomy, ordinary and bit operation, the same method, easy to understand)

topic:

50、Pow(x, n)

Realize pow(x, n), that is, calculate the n-th power function of x (ie, xn).

Example 1:
Insert picture description here
Example 2:
Insert picture description here
Example 3:
Insert picture description here
Prompt:
Insert picture description here

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)

Insert picture description here

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/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/113820505