0
点赞
收藏
分享

微信扫一扫

关于python最大递归深度 - 998

zmhc 2022-03-12 阅读 56


今天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吧~


时间会记录下一切。


举报

相关推荐

0 条评论