[LeetCode]题解(python):050-Pow(x, n)

题目来源:

  https://leetcode.com/problems/powx-n/


 

题意分析:

  实现一个整型的幂运算。


 

题目思路:

  幂运算可以利用二分的方法来做。也就是x^n = x ^ (n /2) * x ^(n / 2) (n %2 == 0)或者x^n = x ^ (n /2) * x ^(n / 2) * x(n %2 == 1)。要注意的时候,当n  < 0 的时候,x ^ n =1 / (x ^(-n))。


 

代码(python):

  

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

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/4953861.html

posted @ 2015-11-10 18:00  Ry_Chen  阅读(994)  评论(0)    收藏  举报