Leetcode练习(Python):递归类:面试题16. 数值的整数次方:实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。

题目:
数值的整数次方:实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
思路:
递归,二分法
程序:
class Solution:
    def myPow(self, x: float, n: int) -> float:
        if x == 0:
            return 0
        if n == 0:
            return 1
        if n == 1:
            return x
        if n >= 0:
            if n % 2 == 0:
                return self.myPow(x * x, n // 2)
            else:
                return self.myPow(x * x, n // 2) * x
        if n < 0:
            if (-n) % 2 == 0:
                return self.myPow(1 / (x * x), (-n) // 2)
            else:
                return self.myPow(1 / (x * x), (-n) // 2) * (1 / x)
posted on 2020-04-27 14:23  桌子哥  阅读(384)  评论(0编辑  收藏  举报