LeetCode 50

LeetCode 50. Pow(x, n)

Implement pow(x, n), which calculates x raised to the power n (x^n).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2^(-2) = 1/2^2 = 1/4 = 0.25

Note:

-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]

解题思路

由题意,需要求出x^n的值,其中x为浮点数,n为整数,x可以为负数,n可以为一个非常大的数。由于n可能非常大,故不能够调用python的内置函数pow()来求解。当n较小时便可以容易的得出乘方的值,故可以应用分治的思想,在每一步减小n的值,再将每一步的结果相乘。由于当n为偶数时,x ^ n = (x * x) ^ (n / 2),当n为奇数时,x ^ n = x * (x * x) ^ (n / 2)。则在每一步对n进行二分,最后可求得x ^ n的值。

源代码

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if n == 0:
            return 1
        if n < 0:
            x = 1 / x
            n = -n
        if n % 2 == 0:
            return self.myPow(x * x, n / 2)
        else:
            return x * self.myPow(x * x, n // 2)

猜你喜欢

转载自blog.csdn.net/abyssalseaa/article/details/80170756