12.数值的整数次方
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
记录
方法一:
直接次方计算,或者使用pow()。
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
return base ** exponent
方法二:
分情况考虑:
base: ==0(返回0) !=0
exponent: <0 ==0(返回1) >0
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
res = 1
if base == 0:
return 0
if exponent == 0:
return 1
if exponent < 0:
for i in range(-exponent):
res *= base
return 1.0/res
if exponent > 0:
for i in range(exponent):
res *= base
return res
方法三: 递归·
a^b
2^5 = 2 * 2^4
2^4 = 2^2 * 2^2
当b是奇数时,a^b = a * a^*(b-1)
当b是偶数时,a^b = a^(b/2) * a^(b/2)
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if exponent == 0:
return 1
if base == 0:
return 0
flag = True
if exponent < 0:
exponent = -exponent
flag = False
if exponent & 1 == 0:
res = self.Power(base, exponent // 2)
res *= res
else:
res = self.Power(base, exponent // 2)
res *= res
res *= base
return res if flag else 1 / res
方法四:快速幂
在方法三的基础上,利用位移实现快速幂。
a^5
5的二进制:0101
5 = 0 * 2 ^ 0 + 1 * 2 ^ 1 + 0 * 2 ^ 2 + 1 * 2 ^ 3
a^5 = a ^ (2 ^ 1) + a ^ (2 ^ 3)
过程:
(1)0101是奇数:res = a
(2)0010 base = a ^ 2
(3)0010是偶数 0001 base = a ^ 4
(4)0001是奇数 res = a * base = a ^ 5
(5)0000结束循环
# -*- coding:utf-8 -*-
class Solution:
def Power(self, base, exponent):
# write code here
if base == 0:
return 0
if exponent == 0:
return 1
e = abs(exponent)
res = 1
while e > 0:
#次方为奇数
if (e & 1 == 1):
res = res * base
e = e>>1
base = base * base
return res if exponent>1 else 1/res