zoukankan      html  css  js  c++  java
  • 16. 数值的整数次方

    方法一:递归写法(分治思想)

    class Solution:
        def myPow(self, x: float, n: int) -> float:
            if n == 0:
                return 1
    
            if n < 0:
                return 1 / self.myPow(x, -n)
    
            # 如果是奇数
            if n & 1:
                return x * self.myPow(x, n - 1)
            return self.myPow(x * x, n >> 1)

    方法二:非递归写法(将指数看成二进制数)

    class Solution:
        def myPow(self, x: float, n: int) -> float:
            if n < 0:
                x = 1 / x
                # 负数变成正数
                n = -n
    
            res = 1
            while n:
                if n & 1:
                    res *= x
                x *= x
                n >>= 1
            return res


    链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/di-gui-xie-fa-fen-zhi-si-xiang-yu-fei-di-gui-xie-f/

  • 相关阅读:
    pymysql
    表查询
    元类
    外键约束
    Mysql知识
    C# windows服务的创建与调试
    JQuery随笔
    jQuery插件开发
    http post和put区别
    NPOI
  • 原文地址:https://www.cnblogs.com/USTC-ZCC/p/12651534.html
Copyright © 2011-2022 走看看