剑指Offer 12. 数值的整数次方 (其他)

Posted on 2018-10-13 12:51  _hqc  阅读(118)  评论(0编辑  收藏  举报

题目描述

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

题目地址

https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=3&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

思路

python中等于没有误差,因此可以写出如下代码

Python

# -*- coding:utf-8 -*-
class Solution:
    def Power(self, base, exponent):
        # write code here
        if base == 0.0:
            return 0
        flag = 0
        if exponent < 0:
            flag = 1
            exponent = -exponent
        res = 1
        for i in range(exponent):
            res *= base
        if flag:
            res = 1.0/res
        return res

if __name__ == '__main__':
    result = Solution().Power(2,-3)
    print(result)