1. 程式人生 > >劍指offer12.數值的整數次方

劍指offer12.數值的整數次方

https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

題目描述
給定一個double型別的浮點數base和int型別的整數exponent。求base的exponent次方。

可以根據遞迴的思想做:

# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        if exponent == 0:
            return 1
        if exponent == 1:
            return base
        if exponent == -1:
            return 1 / base
        if exponent % 2 == 0:
            return self.Power(base, exponent//2) * self.Power(base, exponent//2)
        else:
            return self.Power(base, exponent//2) * self.Power(base, exponent//2 + 1)

運用快速冪演算法。可以取指數的絕對值,然後寫成二進位制的形式,如5為0101,2的五次方可以看成2的一次方乘以2的四次方,從最後一位開始,每次右移一位,底數每次變成原來的平方:

# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        if base == 0:
            return 0
        if exponent == 0:
            return 1
        res, e = 1, abs(exponent)
        while e > 0:
            if e & 1 == 1:
                res = res * base
            base = base * base
            e = e >> 1
        return res if exponent > 0 else 1 / res