算法: 求数幂n次方50. Pow(x, n)

50. Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:

Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:

Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Constraints:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • n is an integer.
  • Either x is not zero or n > 0.
  • -104 <= xn <= 104

1. 二分法解决, 递归解法

算法: 求数幂n次方50. Pow(x, n)_第1张图片
伪代码

func binaryExp(x, n):
    if n == 0: return 1.0
    if n < 0: return 1.0 / binaryExp(x, -n)
   
    // Binary exponentiation steps.
    if n is odd: return x * binaryExp(x * x, (n - 1) / 2)
    otherwise: return binaryExp(x * x, n / 2)
class Solution:
    def myPow(self, x: float, n: int) -> float:
        # 边界条件:如果 n 等于 0,任何数的 0 次方都等于 1。
        if n == 0:
            return 1
       
        # 处理指数 n 为负数的情况
        if n < 0:
            # 使用倒数的方式来计算负数指数的幂
            return 1.0 / self.myPow(x, -1 * n)
       
        # 执行二进制指数计算。
        # 如果 'n' 为奇数,使用二进制指数计算 'n - 1',然后乘以 'x'
        if n % 2 == 1:
            return x * self.myPow(x * x, (n - 1) // 2)
        # 如果 'n' 为偶数,使用二进制指数计算 'n' 的一半
        else:
            return self.myPow(x * x, n // 2)

复杂度分析:

  1. 时间复杂度:O(log n)
    在二进制指数计算中,每次将指数 n 除以 2,因此总共需要进行 log n 次迭代。
  2. 空间复杂度:O(log n)
    递归调用的最大深度是 log n,因此需要额外的空间来存储递归调用的状态。

2. 遍历法解决

class Solution:
    def myPow(self, x: float, n: int) -> float:
        # 边界条件:如果 n 等于 0,任何数的 0 次方都等于 1。
        if n == 0:
            return 1

        # 处理指数 n 为负数的情况
        if n < 0:
            n = -1 * n  # 将负数指数变为正数
            x = 1.0 / x  # 同时将底数 x 变为其倒数

        # 执行二进制指数计算。
        result = 1  # 初始化结果为 1
        while n != 0:
            # 如果 'n' 是奇数,将结果乘以 'x' 并将 'n' 减 1
            if n % 2 == 1:
                result *= x
                n -= 1
            # 如果 'n' 是偶数,将 'x' 自乘并将 'n' 减半,这相当于计算 x 的平方。
            x *= x
            n //= 2

        return result

复杂度分析:

  1. 时间复杂度:O(log n)
    在二进制指数计算中,每次将指数 n 除以 2,因此总共需要进行 log n 次迭代。
  2. 空间复杂度:O(1)
    除了存储结果和中间变量,没有使用额外的空间。

你可能感兴趣的:(算法,算法)