• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Zdz2005

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

[LeeCode] 50. Pow(x, n) python3

题目描述

实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。

 

1.python递归1

class Solution(object):
    def myPow(self, x, n):
        if n == 0 or x == 1 : return 1
        if n == 1: return x
        if n == -1: return 1 / x
        return self.myPow(x, n % 2) * self.myPow(x * x, n//2)

2.python递归2

class Solution(object):
    def myPow(self, x, n):
        if n == 0 or x == 1: return 1
        elif n < 0:
            x = 1/x
            n = -n
        return self.myPow(x*x, n/2) if n % 2 == 0 else x * self.myPow(x*x, n//2)

 

3.python普通算法

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0 or x == 1: return 1
        result = 1.0
        while 0 != n:
            if n % 2 != 0:
                result *= x
                if n == 1 or n == -1:
                    return 1/result if n <0 else result   
            n = int(n/2)
            x *= x
     #return 1/result if n <0 else result

4.python超时算法

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0 or x == 1:return 1
        elif n < 0:
            x = 1/x
            n = -n
        a = x
        for i in range(n -1):
            x *= a
        return x

 

posted on 2021-12-24 21:04  Zdz2005  阅读(40)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3