leetcode50. 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


 

1. recursive

每次由n转成n/2,这样时间复杂度就是log(n)。n为0时,返回1

复制代码
class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0: 
            return 1
        if n < 0:
            return 1 / self.myPow(x, -n)
            # x = 1 / x
            # n = -n
        if n % 2 == 0:
            return self.myPow(x * x, n / 2)
        return x * self.myPow(x, n - 1)
#       return x * self.myPow(x * x, n // 2)
复制代码

 

2. iterative

N = 9 = 2^3 + 2^0 = 1001 in binary. Then:

x^9 = x^(2^3) * x^(2^0)

不断右移二进制n,每当碰到1时,res就乘上n的几次方。右移的同时,x也每次乘自己,相当于走到第i位,x就是x^i。

n & 1 == 0, means divisible by 2

n >>= 1, 二进制右移1位,等效于除2

1
2
3
4
  11 = 00001011 (Not divisible by 2)      28 = 00011100 (Divisible by 2)
1 = 00000001                         1 = 00000001
---------------                         ---------------
       00000001                                00000000
复制代码
class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n < 0:
            n = -n
            x = 1 / x
        res = 1
        while n:
            if n & 1 == 1:
                res *= x
            n >>= 1
            x *= x
        return res
复制代码

 

posted @   aegeanchan  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示