剑指Offer(Python多种思路实现):数值的整数次方
面试16题:
题目:数值的整数次方
题:实现函数double Power(double base, int exponent),求base的exponent次方、不得使用库函数,同时不需要考虑大数问题。
解题思路一:
# 一般方法
class SolutionOne:
def __init__(self):
self.gInvalidInput = False
def inputExp(self, base, exp):
if base==0.0 and exp<0: # 异常情况
self.gInvalidInput=True
return 0.0
if base>=0:
return self.unInputExp(base, exp)
return 1.0/self.unInputExp(base, -exp)
def unInputExp(self, base, exp):
res = 1.0
for i in range(exp):
result *= base
return re
解题思路二:
# 右移or位于运算符
class SolutionTwo:
def myPow(self, x: float, n: int) -> float:
def powWithUnsigned(x, n):
if n==0: return 1
if n==1: return x
ans = powWithUnsigned(x, n>>1)
ans *= ans
if n & 1 == 1:
ans *= x
return ans
if n<0:
return 1 / powWithUnsigned(x, -n)
else:
return powWithUnsigned(x, n)