【剑指offer】数值的整数次方【代码的完整性】

  1. 注意边界情况0的0次方和0的负数次方是没有意义的,面试的时候最好询问到底是返回一个确定的值还是抛出一个异常
  2. 可以使用递归来快速计算提升效率
  3. 用位运算来判断奇数和偶数,用位运算代替除以2,因为位运算的效率比乘除运算和求余运算的效率要高得多
# -*- coding:utf-8 -*-
class Solution:
    def myPower(self, base, exponent):
        if exponent == 0:
            return 1
        if exponent == 1:
            return base
        result = self.myPower(base, exponent >> 1)  #注意位运算要比乘除运算和取余运算效率高很多
        result = result * result
        if exponent & 0x1 == 1:
            result *= base
        return result
    def Power(self, base, exponent):
        # write code here
        if base == 0 and exponent <= 0:
            return 0
        flag = 0
        if exponent < 0:
            flag = 1
        exponent = abs(exponent)
        result = self.myPower(base, exponent)
        if flag == 1:
            result = (float)(1 / result)
        return result
print(Solution().Power(0,-1))

相关文章:

  • 2021-12-01
  • 2022-12-23
  • 2022-12-23
  • 2021-09-30
  • 2021-07-12
  • 2022-01-15
猜你喜欢
  • 2021-09-16
  • 2022-02-19
  • 2021-09-10
  • 2021-12-03
  • 2021-11-20
  • 2022-01-13
相关资源
相似解决方案