layout: post
title: 12-数值的整数次方
category: 剑指offer
tags:
description:
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
- 负幂转为正幂,便于操作。方法:对于a的b次幂
a**b
,如果b<0,则a**b
等价于(1.0/a)**(-b)
。 - 提高效率,有公式:
a**(2b)=(a**b)**2, a**(2b+1)=a*(a**b)**2
class Solution:
def Power(self, base, exponent):
# write code here
def pr(base, expo):
if expo == 0:
return 1
if expo%2 == 1:
return base*pr(base, int(expo/2))**2
else:
return pr(base, int(expo/2))**2
if exponent < 0:
base = 1.0/base
exponent = -exponent
return pr(base, exponent)
转载:https://blog.csdn.net/u012176591/article/details/100916052
查看评论