剑指Offer-数值的整数次方

95 阅读1分钟

题目

实现函数double Power(double base, int exponent) ,求base的 exponent次方。

不得使用库函数,同时不需要考虑大数问题。

只要输出结果与答案的绝对误差不超过 10−210−2 即视为正确。

注意:

  • 不会出现底数和指数同为0的情况
  • 当底数为0时,指数一定为正
  • 底数的绝对值不超过 1010,指数的绝对值不超过 109109。

样例1

输入:10 ,2

输出:100

样例2

输入:10 ,-2  

输出:0.01

解析

使用快速幂(见基础算法快速幂),若exponent小于0,则需要将最后的结果取一个倒数。

代码

C++

class Solution {
public:
    typedef long long LL;
    double Power(double base, int exponent) {
        bool minus = exponent < 0;
        double ans = 1.0;
        for (LL i = abs((LL)exponent); i; i >>= 1) {
            if (i & 1)
                ans *= base;
            base *= base;
        }
        if (minus) {
            return 1 / ans;
        }
        return ans;
    }
};

Python

class Solution(object):
    def Power(self, base, exponent):
        """
        :type base: float
        :type exponent: int
        :rtype: float
        """
        minus = exponent < 0
        ans = 1.0
        k = abs(exponent)
        while k:
            if k&1:
                ans *= base
            base *= base
            k >>= 1
        if minus:
            return 1 / ans
        return ans

GO

func Power(base float64, exponent int) float64 {
    is_minus := exponent < 0
    ans := 1.0
    for k := int64(abs(exponent)); k > 0; k >>= 1 {
        if k & 1 == 1 {
            ans *= base;
        }
        base *= base;
    }
    
    if is_minus {
        ans = 1 / ans
    }
    return ans
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}