剑指offer-数值的整数次方python

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

解法一:直接乘

class Solution:
    def Power(self, base, exponent):
        # write code here
        res=1
        if exponent>0:
            while exponent>0:
                res=res*base
                exponent-=1
            return res
        elif exponent==0:
            return 1
        else:
            while exponent<0:
                res=res/base
                exponent+=1
            return res

解法二:递归

class Solution:
    def Power(self, base, exponent):
        # write code her
        flag=False
        if base==0 and exponent<0:
            flag=True
            return 0
        absexponent=int(exponent) if exponent>0 else int(-exponent)
        result=self.powerWithAbsExponent(base,absexponent)
        if exponent<0:
            result=1.0/result
        return result
      
    def powerWithAbsExponent(self,base,absexponent):
        if absexponent==0:
            return 1
        if absexponent==1:
            return base
        result=self.powerWithAbsExponent(base,absexponent>>1)
        result*=result
        if absexponent&0x1 == 1:
            result*=base
        return result

 

 

你可能感兴趣的:(Python,数据结构与算法,剑指offer)