LeetCode-Python-50. Pow(x, n)

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

示例 1:

输入: 2.00000, 10
输出: 1024.00000

示例 2:

输入: 2.10000, 3
输出: 9.26100

示例 3:

输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25

说明:

  • -100.0 < x < 100.0
  • n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。

第一种思路:

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        return x ** n
        

第二种思路:

按照数学原理进行计算,

先把变量i 设为n的绝对值,

然后依次循环判断,i是否为奇数,如果是,就把res乘上x,

然后把res平方一下,i变成原来的一半。

最后记得处理n为负数的情况。

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        i = abs(n)
        res = 1.0
        while(i != 0):
            if i % 2:
                res *= x
            x *= x
            # print i, res
            i /= 2
        return res if n > 0 else 1/res
        

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/87923818