首页 > 解决方案 > 将 x 幂 n 的解加倍减少

问题描述

我试图解决 leetcode 中的一个 pow(x, n) 问题

实现pow( x , n ),它计算x的n (xn) 次幂。

示例 1:

Input: 2.00000, 10
Output: 1024.00000

示例 2:

Input: 2.10000, 3
Output: 9.26100

示例 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

笔记:

  • -100.0 < x < 100.0
  • n是一个 32 位有符号整数,在 [−231, 231 − 1] 范围内

我的解决方案和测试用例

import unittest
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")
class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if n == 0:
            return 1
        if n < 0:
            return 1 /self.myPow(x, -n)
        else:
            partial = self.myPow(x, n//2)
            logging.debug(f"partial: {partial}")
            result = partial * partial
            if n % 2 == 1: #odd
                result *= x
            else: #even 
                return result

class MyCase(unittest.TestCase):
    def setUp(self):
        self.solution = Solution()

    def test_1(self):
        x = 2
        n = 10
        answer = 1024
        check = self.solution.myPow(x, n)
        self.assertEqual(check, answer)

unittest.main()

它报告错误

In [3]: !python 50.powerxn.py                                                                                                     
DEBUG partial: 1
DEBUG partial: None
E
======================================================================
ERROR: test_1 (__main__.MyCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "50.powerxn.py", line 32, in test_1
    check = self.solution.myPow(x, n)
  File "50.powerxn.py", line 16, in myPow
    partial = self.myPow(x, n//2)
  File "50.powerxn.py", line 16, in myPow
    partial = self.myPow(x, n//2)
  File "50.powerxn.py", line 18, in myPow
    result = partial * partial
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'

我不明白为什么 partial 会得到 None 值?

标签: python

解决方案


在奇怪的情况下你没有返回任何东西,你只是分配

result *= x

将其更改为:

if n % 2 == 1: #odd
    return result * x
else: #even 
    return result

推荐阅读