关于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吧~

猜你喜欢

转载自www.cnblogs.com/bincoding/p/8972238.html