關於python最大遞歸深度 - 998


今天LeetCode的時候暴力求解233

  • 問題:

給定一個整數 n,計算所有小於等於 n 的非負數中數字1出現的個數。

例如:

給定 n = 13,

返回 6,因為數字1出現在下數中出現:1,10,11,12,13。

  • 代碼:
class Solution:
    def __init__(self):
        self.key = '1'
        self.result = 0

    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 1:
            return self.result
        self.result += str(n).count(self.key)
        if n > 0:
            self.countDigitOne(n-1)
        return self.result

s = Solution()
print(s.countDigitOne(11221))
  • 錯誤:

maximum recursion depth exceeded while getting the str of an object

  • 尋找python最大遞歸深度
class Solution:
    def __init__(self):
        self.key = '1'
        self.result = 0

    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 1:
            return self.result
        self.result += str(n).count(self.key)
        if n > 0:
            self.countDigitOne(n-1)
        return self.result

s = Solution()
for i in range(0,1000000):
    print(i)
    print(s.countDigitOne(i))

輸出 998,然后報錯,最大遞歸深度找到了,還是安心用while吧~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM