Implement pow(x, n).
Subscribe to see which companies asked this question
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
result = 1
result_old = 1
flag = n >= 0
flag_x_minus = x < 0
flag_r_minus = False
if flag_x_minus:
x = -x
flag_r_minus = n % 2 == 1
if flag:
for i in xrange(n):
result *= x
if abs(result_old - result) < 0.0000000001:
return result if not flag_r_minus else -result
result_old = result
else:
for i in xrange(-n):
result /= x
if abs(result_old - result) < 0.0000000001:
return result if not flag_r_minus else -result
result_old = result
return result if not flag_r_minus else -result
主要有两点,使用xrange代替range,防止内存Error;判断两次计算的差,小于一定值则结束计算(损失精度)。
运行时间不理想。
class Solution:
# @param x, a float
# @param n, a integer
# @return a float
def pow(self, x, n):
if n < 0:
return 1.0 / self.power(x, -n)
else:
return self.power(x, n)
def power(self, x, n):
if n == 0:
return 1
tmp = self.power(x, n / 2)
if n & 0x01 == 1:
return tmp * tmp * x
else:
return tmp * tmp
一开始没有这种二分的递归思路,长见识了!
这类可以使用二分递归的问题,特点是程序重复相同动作,而且动作的先后顺序无关(类似于数学中的结合律)。