统计0到n中数字0、2、4出现次数的代码问题求助
问题需求
给定数字n,统计从0到n(包含n)的所有数字中,数字0、2、4的出现总次数。
示例
- 示例1:
n = 10 output: 4 - 示例2:
n = 22 output: 11
代码问题
我编写的代码如下:
n = 22 def count_digit(n): count = 0 for i in range(n+1): if '2' in str(i): count += 1 if '0' in str(i): count += 1 if '4' in str(i): count += 1 return count count_digit(n)
代码输出为10,但期望输出是11,需要修正。
约束条件
1 <= N <= 10^5- 解决方案不能引发
outOfMemoryException或Time Limit Exceeded
错误原因
你的代码逻辑有误:仅统计了包含目标数字的数的个数,而非每个数中目标数字的出现次数。比如数字22包含两个2,你的代码只会给计数器加1,但实际应该加2——这就是示例2中结果少1的原因。
修正方案
方案1:遍历每个数字的每一位(简单高效,适配题目约束)
直接修改逻辑,对每个数字的每一位单独检查,每出现一次0/2/4就给计数器加1:
n = 22 def count_digit(n): count = 0 target_digits = {'0', '2', '4'} for num in range(n + 1): # 遍历当前数字的每一位字符 for c in str(num): if c in target_digits: count += 1 return count print(count_digit(n)) # 输出11,符合预期
对于n <= 10^5的场景,这个方案的计算量完全在合理范围内:总共有100001个数字,所有数字的总位数不到5万次,不会出现超时或内存溢出问题。
方案2:数位DP(适配超大数值场景)
如果n的范围远大于105(比如1018),可以用数位DP来优化计算效率,避免逐个数遍历:
def count_digit(n): s = str(n) target_digits = {'0', '2', '4'} length = len(s) from functools import lru_cache @lru_cache(maxsize=None) def dp(pos, current_count, is_tight): # pos:当前处理的数位位置 # current_count:已统计的目标数字次数 # is_tight:当前数位是否受原数字的上限约束 if pos == length: return current_count max_digit = int(s[pos]) if is_tight else 9 total = 0 for d in range(0, max_digit + 1): new_tight = is_tight and (d == max_digit) add = 1 if str(d) in target_digits else 0 total += dp(pos + 1, current_count + add, new_tight) return total return dp(0, 0, True) print(count_digit(22)) # 输出11
该方法通过记忆化搜索避免重复计算,大幅提升超大数值下的计算效率。
内容的提问来源于stack exchange,提问作者meallhour
相关产品推荐
相关产品推荐

