码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-11-10 19:30:59      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:

  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

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

标签:

原文地址:http://www.cnblogs.com/chruny/p/4953861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!