Violent solution 233 in LeetCode today
- question:
Given an integer n, count the number of occurrences of the number 1 in all non-negative numbers less than or equal to n.
E.g:
Given n = 13,
Returns 6, because the number 1 appears in the following numbers: 1, 10, 11, 12, 13.
- Code:
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))
- mistake:
maximum recursion depth exceeded while getting the str of an object
- Find python maximum recursion depth
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))
Output 998, and then report an error, the maximum recursion depth is found, or use while with peace of mind~