[剑指Offer]数值的整数次方

题目描述

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

解题思路

使用递归的方法,将整数次幂除2,底数变为原来的平方。不能整除的向下取整,再多乘一个底数。指数为负时将底数取倒数,指数变正。
特殊输入测试:底数为0,指数为负的无效输入;指数为负。

代码

Python(2.7.3)

投机取巧法

这道题目本来是出给C#/C++的答题者,考察代码的完整性,但奈何Python面向对象太强大……呸!以题解题还有理了……

1
2
3
4
5
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
return base ** exponent

运行时间:23ms
占用内存:5624k

正常递归解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if base == 0 and exponent < 0:
raise ValueError("Please enter valid numbers!")
elif exponent == 0:
return 1
elif exponent == 1:
return base
elif exponent < 0:
base = 1 / base
exponent = -exponent
if exponent % 2 == 0:
return self.Power(base * base, exponent / 2)
else:
return self.Power(base * base, exponent // 2) * base

运行时间:31ms
占用内存:5712k