50、Pow(x, n)

来源:互联网 发布:淘宝店铺号 编辑:程序博客网 时间:2024/05/22 02:51

题目:

Implement pow(xn).

解题思路:

二分法,O(lgn)。

python版本:

class Solution(object):    def myPow(self, x, n):        """        :type x: float        :type n: int        :rtype: float        """        if(n==0):            return 1.0        elif(n>0):            if(n&1):                return (self.myPow(x, n/2)**2)*x            else:                return (self.myPow(x, n/2)**2)        else:            return 1.0/self.myPow(x,abs(n))        
c++版本

class Solution {public:    double myPow2(double x, int n){        if(n==0)            return 1.0;        else            return (n&1) ? pow(myPow2(x,n/2),2)*x : pow(myPow2(x,n/2),2);    }    double myPow(double x, int n) {        if(n>=0)            return myPow2(x,n);        else            return 1.0/myPow2(x,-n);            }};



0 0
原创粉丝点击